Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count Primes in Ranges
Next article icon

Range Queries for Frequencies of array elements

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type.

Examples: 

Input  : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};           left = 2, right = 8, element = 8           left = 2, right = 5, element = 6        Output : 3           1  The element 8 appears 3 times in arr[left-1..right-1]  The element 6 appears 1 time in arr[left-1..right-1]

Naive approach: is to traverse from left to right and update count variable whenever we find the element. 

Below is the code of Naive approach:- 

C++




// C++ program to find total count of an element
// in a range
#include<bits/stdc++.h>
using namespace std;
  
// Returns count of element in arr[left-1..right-1]
int findFrequency(int arr[], int n, int left,
                         int right, int element)
{
    int count = 0;
    for (int i=left-1; i<=right; ++i)
        if (arr[i] == element)
            ++count;
    return count;
}
  
// Driver Code
int main()
{
    int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Print frequency of 2 from position 1 to 6
    cout << "Frequency of 2 from 1 to 6 = "
         << findFrequency(arr, n, 1, 6, 2) << endl;
  
    // Print frequency of 8 from position 4 to 9
    cout << "Frequency of 8 from 4 to 9 = "
         << findFrequency(arr, n, 4, 9, 8);
  
    return 0;
}
 
 

Java




// JAVA Code to find total count of an element
// in a range
  
class GFG {
      
    // Returns count of element in arr[left-1..right-1]
    public static int findFrequency(int arr[], int n, 
                                int left, int right,
                                      int element)
    {
        int count = 0;
        for (int i = left - 1; i < right; ++i)
            if (arr[i] == element)
                ++count;
        return count;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
        int n = arr.length;
       
        // Print frequency of 2 from position 1 to 6
        System.out.println("Frequency of 2 from 1 to 6 = " +
             findFrequency(arr, n, 1, 6, 2));
       
        // Print frequency of 8 from position 4 to 9
        System.out.println("Frequency of 8 from 4 to 9 = " +
             findFrequency(arr, n, 4, 9, 8));
          
    }
  } 
// This code is contributed by Arnav Kr. Mandal.
 
 

Python3




# Python program to find total  
# count of an element in a range
  
# Returns count of element
# in arr[left-1..right-1]
def findFrequency(arr, n, left, right, element):
  
    count = 0
    for i in range(left - 1, right):
        if (arr[i] == element):
            count += 1
    return count
  
  
# Driver Code
arr = [2, 8, 6, 9, 8, 6, 8, 2, 11]
n = len(arr)
  
# Print frequency of 2 from position 1 to 6
print("Frequency of 2 from 1 to 6 = ",
        findFrequency(arr, n, 1, 6, 2))
  
# Print frequency of 8 from position 4 to 9
print("Frequency of 8 from 4 to 9 = ",
        findFrequency(arr, n, 4, 9, 8))
          
      
# This code is contributed by Anant Agarwal.
 
 

C#




// C# Code to find total count 
// of an element in a range
using System;
  
class GFG {
      
    // Returns count of element 
    // in arr[left-1..right-1]
    public static int findFrequency(int []arr, int n, 
                                    int left, int right,
                                    int element)
    {
        int count = 0;
        for (int i = left - 1; i < right; ++i)
            if (arr[i] == element)
                ++count;
        return count;
    }
      
    // Driver Code
    public static void Main() 
    {
        int []arr = {2, 8, 6, 9, 8, 6, 8, 2, 11};
        int n = arr.Length;
      
        // Print frequency of 2 
        // from position 1 to 6
        Console.WriteLine("Frequency of 2 from 1 to 6 = " +
                            findFrequency(arr, n, 1, 6, 2));
      
        // Print frequency of 8 
        // from position 4 to 9
        Console.Write("Frequency of 8 from 4 to 9 = " +
                       findFrequency(arr, n, 4, 9, 8));
          
    }
} 
  
// This code is contributed by Nitin Mittal.
 
 

PHP




<?php
// PHP program to find total count of 
// an element in a range
  
// Returns count of element in 
// arr[left-1..right-1]
function findFrequency(&$arr, $n, $left,
                        $right, $element)
{
    $count = 0;
    for ($i = $left - 1; $i <= $right; ++$i)
        if ($arr[$i] == $element)
            ++$count;
    return $count;
}
  
// Driver Code
$arr = array(2, 8, 6, 9, 8, 6, 8, 2, 11);
$n = sizeof($arr);
  
// Print frequency of 2 from position 1 to 6
echo "Frequency of 2 from 1 to 6 = ". 
      findFrequency($arr, $n, 1, 6, 2) ."\n";
  
// Print frequency of 8 from position 4 to 9
echo "Frequency of 8 from 4 to 9 = ". 
      findFrequency($arr, $n, 4, 9, 8);
  
// This code is contributed by ita_c
?>
 
 

Javascript




<script>
  
// Javascript Code to find total count of an element
// in a range
      
    // Returns count of element in arr[left-1..right-1]
    function findFrequency(arr,n,left,right,element)
    {
        let count = 0;
        for (let i = left - 1; i < right; ++i)
            if (arr[i] == element)
                ++count;
        return count;
    }
      
    /* Driver program to test above function */
    let arr=[2, 8, 6, 9, 8, 6, 8, 2, 11];
    let n = arr.length;
      
    // Print frequency of 2 from position 1 to 6
    document.write("Frequency of 2 from 1 to 6 = " +
             findFrequency(arr, n, 1, 6, 2)+"<br>");
      
    // Print frequency of 8 from position 4 to 9
    document.write("Frequency of 8 from 4 to 9 = " +
             findFrequency(arr, n, 4, 9, 8));
      
    // This code is contributed by rag2127
      
</script>
 
 
Output
Frequency of 2 from 1 to 6 = 1  Frequency of 8 from 4 to 9 = 2

Time complexity of this approach is O(right – left + 1) or O(n) 
Auxiliary space: O(1)

An Efficient approach is to use hashing. In C++, we can use unordered_map

  • At first, we will store the position in map[] of every distinct element as a vector like that 
  int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};    map[2] = {1, 8}    map[8] = {2, 5, 7}    map[6] = {3, 6}     ans so on...
  • As we can see that elements in map[] are already in sorted order (Because we inserted elements from left to right), the answer boils down to find the total count in that hash map[] using binary search like method. 
     
  • In C++ we can use lower_bound which will returns an iterator pointing to the first element in the range [first, last] which has a value not less than ‘left’. and upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘right’. 
     
  • After that we just need to subtract the upper_bound() and lower_bound() result to get the final answer. For example, suppose if we want to find the total count of 8 in the range from [1 to 6], then the map[8] of lower_bound() function will return the result 0 (pointing to 2) and upper_bound() will return 2 (pointing to 7), so we need to subtract the both the result like 2 – 0 = 2 . 
     

Below is the code of above approach 

C++




// C++ program to find total count of an element
#include<bits/stdc++.h>
using namespace std;
  
unordered_map< int, vector<int> > store;
  
// Returns frequency of element in arr[left-1..right-1]
int findFrequency(int arr[], int n, int left,
                      int right, int element)
{
    // Find the position of first occurrence of element
    int a = lower_bound(store[element].begin(),
                        store[element].end(),
                        left)
            - store[element].begin();
  
    // Find the position of last occurrence of element
    int b = upper_bound(store[element].begin(),
                        store[element].end(),
                        right)
            - store[element].begin();
  
    return b-a;
}
  
// Driver code
int main()
{
    int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Storing the indexes of an element in the map
    for (int i=0; i<n; ++i)
        store[arr[i]].push_back(i+1); //starting index from 1
  
    // Print frequency of 2 from position 1 to 6
    cout << "Frequency of 2 from 1 to 6 = "
         << findFrequency(arr, n, 1, 6, 2) <<endl;
  
    // Print frequency of 8 from position 4 to 9
    cout << "Frequency of 8 from 4 to 9 = "
         << findFrequency(arr, n, 4, 9, 8);
  
    return 0;
}
 
 

Java




// Java program to find total count of an element
import java.util.*;
  
public class GFG {
  
  static HashMap<Integer, ArrayList<Integer> > store;
  
  static int lower_bound(ArrayList<Integer> a, int low,
                         int high, int key)
  {
    if (low > high) {
      return low;
    }
    int mid = low + (high - low) / 2;
    if (key <= a.get(mid)) {
  
      return lower_bound(a, low, mid - 1, key);
    }
    return lower_bound(a, mid + 1, high, key);
  }
  
  static int upper_bound(ArrayList<Integer> a, int low,
                         int high, int key)
  {
    if (low > high || low == a.size())
      return low;
    int mid = low + (high - low) / 2;
    if (key >= a.get(mid)) {
      return upper_bound(a, mid + 1, high, key);
    }
    return upper_bound(a, low, mid - 1, key);
  }
  
  // Returns frequency of element in arr[left-1..right-1]
  static int findFrequency(int arr[], int n, int left,
                           int right, int element)
  {
    // Find the position of first occurrence of element
    int a
      = lower_bound(store.get(element), 0,
                    store.get(element).size(), left);
  
    // Find the position of last occurrence of element
    int b
      = upper_bound(store.get(element), 0,
                    store.get(element).size(), right);
  
    return b - a;
  }
  
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 2, 8, 6, 9, 8, 6, 8, 2, 11 };
    int n = arr.length;
  
    // Storing the indexes of an element in the map
    store = new HashMap<>();
    for (int i = 0; i < n; ++i) {
      if (!store.containsKey(arr[i]))
        store.put(arr[i], new ArrayList<>());
      store.get(arr[i]).add(
        i + 1); // starting index from 1
    }
  
    // Print frequency of 2 from position 1 to 6
    System.out.println(
      "Frequency of 2 from 1 to 6 = "
      + findFrequency(arr, n, 1, 6, 2));
  
    // Print frequency of 8 from position 4 to 9
    System.out.println(
      "Frequency of 8 from 4 to 9 = "
      + findFrequency(arr, n, 4, 9, 8));
  }
}
  
// This code is contributed by Karandeep1234
 
 

Python3




# Python3 program to find total count of an element
from collections import defaultdict as dict
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound
  
store = dict(list)
  
# Returns frequency of element 
# in arr[left-1..right-1]
def findFrequency(arr, n, left, right, element):
      
    # Find the position of 
    # first occurrence of element
    a = lower_bound(store[element], left)
  
    # Find the position of
    # last occurrence of element
    b = upper_bound(store[element], right)
  
    return b - a
  
# Driver code
arr = [2, 8, 6, 9, 8, 6, 8, 2, 11]
n = len(arr)
  
# Storing the indexes of
# an element in the map
for i in range(n):
    store[arr[i]].append(i + 1)
  
# Print frequency of 2 from position 1 to 6
print("Frequency of 2 from 1 to 6 = ", 
       findFrequency(arr, n, 1, 6, 2))
  
# Print frequency of 8 from position 4 to 9
print("Frequency of 8 from 4 to 9 = ",
       findFrequency(arr, n, 4, 9, 8))
  
# This code is contributed by Mohit Kumar
 
 

C#




// C# program to find total count of an element
  
using System;
using System.Collections;
using System.Collections.Generic;
  
public class GFG {
  
    static Dictionary<int, List<int> > store;
  
    static int lower_bound(List<int> a, int low, int high,
                           int key)
    {
        if (low > high) {
            return low;
        }
        int mid = low + (high - low) / 2;
        if (key <= a[mid]) {
  
            return lower_bound(a, low, mid - 1, key);
        }
        return lower_bound(a, mid + 1, high, key);
    }
  
    static int upper_bound(List<int> a, int low, int high,
                           int key)
    {
        if (low > high || low == a.Count)
            return low;
        int mid = low + (high - low) / 2;
        if (key >= a[mid]) {
            return upper_bound(a, mid + 1, high, key);
        }
        return upper_bound(a, low, mid - 1, key);
    }
  
    // Returns frequency of element in arr[left-1..right-1]
    static int findFrequency(int[] arr, int n, int left,
                             int right, int element)
    {
        // Find the position of first occurrence of element
        int a = lower_bound(store[element], 0,
                            store[element].Count, left);
  
        // Find the position of last occurrence of element
        int b = upper_bound(store[element], 0,
                            store[element].Count, right);
  
        return b - a;
    }
  
    // Driver code
    public static void Main(string[] args)
    {
        int[] arr = { 2, 8, 6, 9, 8, 6, 8, 2, 11 };
        int n = arr.Length;
  
        // Storing the indexes of an element in the map
        store = new Dictionary<int, List<int> >();
        for (int i = 0; i < n; ++i) {
            if (!store.ContainsKey(arr[i]))
                store.Add(arr[i], new List<int>());
            store[arr[i]].Add(i
                              + 1); // starting index from 1
        }
  
        // Print frequency of 2 from position 1 to 6
        Console.WriteLine("Frequency of 2 from 1 to 6 = "
                          + findFrequency(arr, n, 1, 6, 2));
  
        // Print frequency of 8 from position 4 to 9
        Console.WriteLine("Frequency of 8 from 4 to 9 = "
                          + findFrequency(arr, n, 4, 9, 8));
    }
}
  
// This code is contributed by Karandeep1234
 
 

Javascript




   var store = null;
  function lower_bound(a, low, high, key)
  {
      if (low > high)
      {
          return low;
      }
      var mid = low + parseInt((high - low) / 2);
      if (key <= a[mid])
      {
          return lower_bound(a, low, mid - 1, key);
      }
      return lower_bound(a, mid + 1, high, key);
  }
  function upper_bound(a, low, high, key)
  {
      if (low > high || low == a.length)
      {
          return low;
      }
      var mid = low + parseInt((high - low) / 2);
      if (key >= a[mid])
      {
          return upper_bound(a, mid + 1, high, key);
      }
      return upper_bound(a, low, mid - 1, key);
  }
    
  // Returns frequency of element in arr[left-1..right-1]
  function findFrequency(arr, n, left, right, element)
  {
    
      // Find the position of first occurrence of element
      var a = lower_bound(store.get(element), 0, store.get(element).length, left);
        
      // Find the position of last occurrence of element
      var b = upper_bound(store.get(element), 0, store.get(element).length, right);
      return b - a;
  }
  // Driver code
    
      var arr = [2, 8, 6, 9, 8, 6, 8, 2, 11];
      var n = arr.length;
        
      // Storing the indexes of an element in the map
      store = new Map();
      var i=0;
      for (i; i < n; ++i)
      {
          if (!store.has(arr[i]))
          {
              store.set(arr[i],new Array());
          }
          (store.get(arr[i]).push(i + 1) > 0);
      }
        
      // Print frequency of 2 from position 1 to 6
      console.log("Frequency of 2 from 1 to 6 = " + findFrequency(arr, n, 1, 6, 2));
        
      // Print frequency of 8 from position 4 to 9
      console.log("Frequency of 8 from 4 to 9 = " + findFrequency(arr, n, 4, 9, 8));
  
// This code is contributed by sourabhdalal0001.
 
 
Output
Frequency of 2 from 1 to 6 = 1  Frequency of 8 from 4 to 9 = 2

This approach will be beneficial if we have a large number of queries of an arbitrary range asking the total frequency of particular element.
Time complexity: O(log N) for single query.
Auxiliary Space: O(N)

 



Next Article
Count Primes in Ranges

S

Shubham Bansal
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • array-range-queries
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • PreComputation Technique on Arrays
    Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as
    15 min read
  • Queries for the product of first N factorials
    Given Q[] queries where each query consists of an integer N, the task is to find the product of first N factorials for each of the query. Since the result could be large, compute it modulo 109 + 7.Examples: Input: Q[] = {4, 5} Output: 288 34560 Query 1: 1! * 2! * 3! * 4! = 1 * 2 * 6 * 24 = 288 Query
    7 min read
  • Range sum queries without updates
    Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples: Input : arr[] = {1, 2, 3, 4, 5} i = 1, j = 3 i = 2, j = 4Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i
    6 min read
  • Range Queries for Frequencies of array elements
    Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
    13 min read
  • Count Primes in Ranges
    Given a 2d array queries[][] of size n, where each query queries[i] contain 2 elements [l, r], your task is to find the count of number of primes in inclusive range [l, r] Examples: Input: queries[][] = [ [1, 10], [5, 10], [11, 20] ]Output: 4 2 4Explanation: For query 1, number of primes in range [1
    12 min read
  • Check in binary array the number represented by a subarray is odd or even
    Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
    4 min read
  • GCDs of given index ranges in an Array
    Given an array arr[] of size N and Q queries of type {qs, qe} where qs and qe denote the starting and ending index of the query, the task is to find the GCD of all the numbers in the range. Examples: Input: arr[] = {2, 3, 60, 90, 50};Index Ranges: {1, 3}, {2, 4}, {0, 2}Output: GCDs of given ranges a
    14 min read
  • Mean of range in array
    Given an array arr[] of n integers and q queries represented by an array queries[][], where queries[i][0] = l and queries[i][1] = r. For each query, the task is to calculate the mean of elements in the range l to r and return its floor value. Examples: Input: arr[] = [3, 7, 2, 8, 5] queries[][] = [[
    12 min read
  • Difference Array | Range update query in O(1)
    You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where: [1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).[2]: Prints the current state of the array.You need to perform the queries in order. Examples : Input: arr[] = [10
    11 min read
  • Range sum query using Sparse Table
    We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and q
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences