Open In App

Range Queries for Frequencies of array elements

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
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)

 



Previous Article
Next Article

Similar Reads

Java Program for 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}; left = 2, right = 8, element = 8 left = 2, right =
2 min read
Php Program for 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}; left = 2, right = 8, element = 8 left = 2, right =
2 min read
Javascript Program for 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}; left = 2, right = 8, element = 8 left = 2, right =
2 min read
C++ Program for 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}; left = 2, right = 8, element = 8 left = 2, right =
4 min read
Python3 Program for 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}; left = 2, right = 8, element = 8 left = 2, right = 5,
4 min read
Array range queries over range queries
Given an array of size n and a give set of commands of size m. The commands are enumerated from 1 to m. These commands can be of the following two types of commands: Type 1 [l r (1 &lt;= l &lt;= r &lt;= n)] : Increase all elements of the array by one, whose indices belongs to the range [l, r]. In these queries of the index is inclusive in the range
15+ min read
Queries to count frequencies of a given character in a given range of indices
Given a string S of length N and an array Q[][] of queries in the form {l, r, y}. For each query, the task is to print the number of characters y present in the range [l, r]. Examples: Input: S = "aabv", Q[][] = {{0, 3, 'a'}, {1, 2, 'b'}}Output: 2 1Explanation:Query 1: Number of character 'a' present in the range [0, 3] is 2.Query 2: Number of char
7 min read
Find array elements with frequencies in range [l , r]
Given an array of integers, find the elements from the array whose frequency lies in the range [l, r]. Examples: Input : arr[] = { 1, 2, 3, 3, 2, 2, 5 } l = 2, r = 3 Output : 2 3 3 2 2 Approach : Take a hash map, which will store the frequency of all the elements in the array.Now, traverse once again.Print the elements whose frequency lies between
9 min read
POTD Solutions | 1 Nov’ 23 | Frequencies of Limited Range Array Elements
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Frequency Counting algorithm but will also help you build up problem-solving skills. We recommend you to
7 min read
Range Queries to count elements lying in a given Range : MO's Algorithm
Given an array arr[] of N elements and two integers A to B, the task is to answer Q queries each having two integers L and R. For each query, find the number of elements in the subarray arr[L…R] which lies within the range A to B (inclusive). Examples: Input: arr[] = {7, 3, 9, 13, 5, 4}, A = 4, B = 7query = {1, 5}Output: 2Explanation:Only 5 and 4 l
15+ min read
Practice Tags :