Find frequency of the elements in given ranges
Last Updated :
14 Mar, 2023
Given a 2-dimensional integer array arr[] representing N ranges, each of type [starti, endi] (starti, endi ≤ 109) and Q queries represented in array query[], the task is to find the maximum occurrence of query[i] (query[i] ≤ 109) in the given ranges for all i in the range [0, Q-1].
Examples:
Input: arr[] = {{1, 5}, {3, 6}, {5, 7}, {12, 15}}, query[] = {1, 3, 5, 13}
Output: {1, 2, 3, 1}
Explanation: The occurrence of 1 in the range is 1.
The occurrence of 3 in the range is 2.
The occurrence of 5 in the range is 3.
The occurrence of 13 in the range is 1.
Input: arr[] = {{2, 5}, {9, 11}, {3, 9}, {15, 20}}, query[] = {3, 9, 16, 55}
Output: {2, 2, 1, 0}
Naive approach: For each query, traverse the array and check whether query[j] is in the range of arr[i] = [starti, endi]. If it is in the range then increment the counter for the occurrence of that element and store this counter corresponding to query[j] in the result.
Time Complexity: O(Q * N)
Auxiliary Space: O(1)
Efficient approach: The problem can be solved based on the following idea:
Use the technique of prefix sum to store the occurrences of each element and it will help to find the answer for each query in constant time.
Follow the steps below to implement the above idea:
- Declare a one-dimensional array (say prefixSum[]) of length M (where M is the maximum element in arr[]) to store the occurrence of each element.
- Iterate over the array arr[] and do the following for each starti and endi :
- Increment the value at prefixSum[starti] by 1
- Decrement the value at prefixSum[endi + 1] by 1
- Iterate over prefixSum[] array and calculate prefix sum. Using this, the occurrences of each element in the given ranges will get calculated
- Iterate over the queries array and for each query get the value of prefixSum[query[i]] and store it into the resultant array.
- Return the result array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 10000000
void findTheOccurrence(vector<vector< int > >& arr,
vector< int >& q,
vector< int >& result)
{
vector< int > prefixSum(MAX);
for ( int i = 0; i < arr.size(); i++) {
int start = arr[i][0];
int end = arr[i][1];
prefixSum[start]++;
prefixSum[end + 1]--;
}
for ( int i = 1; i < prefixSum.size(); i++) {
prefixSum[i]
= prefixSum[i - 1] + prefixSum[i];
}
for ( int i = 0; i < q.size(); i++) {
int occurrence = prefixSum[q[i]];
result.push_back(occurrence);
}
}
int main()
{
vector<vector< int > > arr
= { { 1, 5 }, { 3, 6 }, { 5, 7 }, { 12, 15 } };
vector< int > query = { 1, 3, 5, 13 };
vector< int > result;
findTheOccurrence(arr, query, result);
for ( auto i : result)
cout << i << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int MAX = 10000000 ;
static void findTheOccurrence( int [][] arr, int [] q,
ArrayList<Integer> result)
{
int [] prefixSum = new int [(MAX)];
for ( int i = 0 ; i < arr.length; i++) {
int start = arr[i][ 0 ];
int end = arr[i][ 1 ];
prefixSum[start]++;
prefixSum[end + 1 ]--;
}
for ( int i = 1 ; i < prefixSum.length; i++) {
prefixSum[i]
= prefixSum[i - 1 ] + prefixSum[i];
}
for ( int i = 0 ; i < q.length; i++) {
int occurrence = prefixSum[q[i]];
result.add(occurrence);
}
}
public static void main(String args[])
{
int [][] arr
= { { 1 , 5 }, { 3 , 6 }, { 5 , 7 }, { 12 , 15 } };
int [] query = { 1 , 3 , 5 , 13 };
ArrayList<Integer> result
= new ArrayList<Integer>();
findTheOccurrence(arr, query, result);
for ( int i : result)
System.out.print(i + " " );
}
}
|
Python3
MAX = 10000 ;
def findTheOccurrence(arr, q, result):
prefixSum = [ 0 ] * MAX
for i in range ( len (arr)):
start = arr[i][ 0 ];
end = arr[i][ 1 ];
prefixSum[start] + = 1
prefixSum[end + 1 ] - = 1
for i in range ( 1 , len (prefixSum)):
prefixSum[i] = prefixSum[i - 1 ] + prefixSum[i];
for i in range ( 0 , len (q)):
occurrence = prefixSum[q[i]];
result.append(occurrence);
return result;
arr = [[ 1 , 5 ], [ 3 , 6 ], [ 5 , 7 ], [ 12 , 15 ] ];
query = [ 1 , 3 , 5 , 13 ];
result = [];
findTheOccurrence(arr, query, result);
for i in range ( len (result)):
print (result[i], end = " " );
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MAX = 10000000;
static void findTheOccurrence( int [,] arr, int [] q,
List< int > result)
{
int [] prefixSum = new int [(MAX)];
for ( int i = 0; i < arr.GetLength(0); i++) {
int start = arr[i, 0];
int end = arr[i, 1];
prefixSum[start]++;
prefixSum[end + 1]--;
}
for ( int i = 1; i < prefixSum.Length; i++) {
prefixSum[i]
= prefixSum[i - 1] + prefixSum[i];
}
for ( int i = 0; i < q.Length; i++) {
int occurrence = prefixSum[q[i]];
result.Add(occurrence);
}
}
public static void Main()
{
int [,] arr
= { { 1, 5 }, { 3, 6 }, { 5, 7 }, { 12, 15 } };
int [] query = { 1, 3, 5, 13 };
List< int > result
= new List< int >();
findTheOccurrence(arr, query, result);
foreach ( int i in result)
Console.Write(i + " " );
}
}
|
Javascript
<script>
let MAX = 10000;
function findTheOccurrence(arr, q, result)
{
prefixSum = new Array(MAX).fill(0);
for ( var i = 0; i < arr.length; i++)
{
var start = arr[i][0];
var end = arr[i][1];
prefixSum[start]++;
prefixSum[end + 1]--;
}
for ( var i = 1; i < prefixSum.length; i++) {
prefixSum[i] = prefixSum[i - 1] + prefixSum[i];
}
for ( var i = 0; i < q.length; i++) {
var occurrence = prefixSum[q[i]];
result.push(occurrence);
}
return result;
}
var arr = [[ 1, 5 ], [ 3, 6 ], [ 5, 7 ], [ 12, 15 ] ];
var query = [ 1, 3, 5, 13 ];
var result = [];
findTheOccurrence(arr, query, result);
for ( var i = 0; i < result.length; i++)
document.write(result[i] + " " );
</script>
|
Time Complexity: O(M), where M is the maximum element of the array.
Auxiliary Space: O(MAX)
Note: This approach will not work here because of the given constraints
Space Optimized approach: The idea is similar to the above approach, but there will be the following changes:
We will use a map to store the frequency of elements in given ranges instead of creating a prefix sum array. If the range of elements in arr[] is high as 109 then we can not create such a big length array. But in the map (ordered map) we can calculate the prefix sum while iterating over the map and can perform the rest of the operations as done in the above approach.
Follow the steps below to implement the above idea:
- Create a map (ordered map), where the key represents the element and the value represents the frequency of the key.
- Iterate over arr[]:
- Increment the frequency of starti by 1
- Decrement the frequency of (endi + 1) by 1
- Initialize two arrays to store the elements that appear in the map and the frequencies corresponding to that element.
- Iterate over the map and use prefix sum technique to calculate the frequency of each element and store them in the created arrays.
- Iterate over the query array and for each query:
- Find the closest integer (say x) which just greater or equal to query[i] and is present in the map.
- Check if x and query[i] are the same:
- If they are the same then the corresponding frequency of x is the required frequency.
- Otherwise, the frequency of the elements corresponding to the element just before x is the answer.
- Store this frequency in the resultant array.
- Return the result array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > findTheOccurrence(vector<vector< int > >& arr,
vector< int >& q,
vector< int >& result)
{
int n = arr.size();
map< long long , long long > mp;
for ( auto & i : arr) {
mp[i[0]]++;
mp[( long long )i[1] + 1]--;
}
vector< long long > range, freq;
long long prefixSum = 0;
for ( auto i : mp) {
prefixSum = prefixSum
+ ( long long )i.second;
range.push_back(i.first);
freq.push_back(prefixSum);
}
for ( auto p : q) {
int idx = lower_bound(range.begin(),
range.end(), p)
- range.begin();
if (idx >= 0 && idx < range.size()) {
if (range[idx] != p)
idx--;
if (idx >= 0)
result.push_back(freq[idx]);
else
result.push_back(0);
}
else {
result.push_back(freq[range.size()
- 1]);
}
}
return result;
}
int main()
{
vector<vector< int > > arr
= { { 1, 5 }, { 3, 6 }, { 5, 7 }, { 12, 15 } };
vector< int > q = { 1, 3, 5, 13 };
vector< int > result;
findTheOccurrence(arr, q, result);
for ( auto i : result)
cout << i << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int lower_bound(ArrayList<Integer> arr, int ele)
{
for (var i = 0 ; i < arr.size(); i++) {
if (arr.get(i) >= ele)
return i;
}
return arr.size();
}
static ArrayList<Integer>
findTheOccurrence( int [][] arr, int [] q,
ArrayList<Integer> result)
{
int n = arr.length;
TreeMap<Integer, Integer> mp
= new TreeMap<Integer, Integer>();
for ( int i = 0 ; i < arr.length; i++) {
if (!mp.containsKey(arr[i][ 0 ]))
mp.put(arr[i][ 0 ], 0 );
if (!mp.containsKey(arr[i][ 1 ] + 1 ))
mp.put(arr[i][ 1 ] + 1 , 0 );
mp.put(arr[i][ 0 ], mp.get(arr[i][ 0 ]) + 1 );
mp.put(arr[i][ 1 ] + 1 ,
mp.get(arr[i][ 1 ] + 1 ) - 1 );
}
ArrayList<Integer> range = new ArrayList<Integer>();
ArrayList<Integer> freq = new ArrayList<Integer>();
int prefixSum = 0 ;
for (Map.Entry<Integer, Integer> i :
mp.entrySet()) {
prefixSum = prefixSum + i.getValue();
range.add(i.getKey());
freq.add(prefixSum);
}
for (Integer p : q) {
int idx = lower_bound(range, p);
if (idx >= 0 && idx < range.size()) {
if (range.get(idx) != p)
idx--;
if (idx >= 0 )
result.add(freq.get(idx));
else
result.add( 0 );
}
else {
result.add(freq.get(range.size() - 1 ));
}
}
return result;
}
public static void main(String[] args)
{
int [][] arr
= { { 1 , 5 }, { 3 , 6 }, { 5 , 7 }, { 12 , 15 } };
int [] q = { 1 , 3 , 5 , 13 };
ArrayList<Integer> result
= new ArrayList<Integer>();
findTheOccurrence(arr, q, result);
for (Integer i : result)
System.out.print(i + " " );
}
}
|
Python3
import bisect
def findTheOccurrence(arr, q, result):
n = len (arr)
mp = {}
for i in arr:
if i[ 0 ] not in mp:
mp[i[ 0 ]] = 0
if (i[ 1 ] + 1 ) not in mp:
mp[i[ 1 ] + 1 ] = 0
mp[i[ 0 ]] + = 1
mp[i[ 1 ] + 1 ] - = 1
range = []
freq = []
prefixSum = 0
for i in sorted (mp.keys()):
prefixSum = prefixSum + mp[i]
range .append(i)
freq.append(prefixSum)
for p in q:
idx = bisect.bisect_left( range , p)
if (idx > = 0 and idx < len ( range )):
if ( range [idx] ! = p):
idx - = 1
if (idx > = 0 ):
result.append(freq[idx])
else :
result.append( 0 )
else :
result.append(freq[ len ( range ) - 1 ])
return result
arr = [[ 1 , 5 ], [ 3 , 6 ], [ 5 , 7 ], [ 12 , 15 ] ]
q = [ 1 , 3 , 5 , 13 ]
result = []
result = findTheOccurrence(arr, q, result);
print ( " " .join( list ( map ( str , result))))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int lower_bound(List< int > arr, int ele)
{
for ( var i = 0; i < arr.Count; i++) {
if (arr[i] >= ele)
return i;
}
return arr.Count;
}
static List< int > findTheOccurrence( int [, ] arr, int [] q,
List< int > result)
{
Dictionary< int , int > mp
= new Dictionary< int , int >();
for ( int i = 0; i < arr.GetLength(0); i++) {
if (!mp.ContainsKey(arr[i, 0]))
mp[arr[i, 0]] = 0;
if (!mp.ContainsKey(arr[i, 1] + 1))
mp[arr[i, 1] + 1] = 0;
mp[arr[i, 0]] += 1;
mp[arr[i, 1] + 1] -= 1;
}
List< int > range = new List< int >();
List< int > freq = new List< int >();
int prefixSum = 0;
var mpKeys = new List< int >(mp.Keys);
mpKeys.Sort();
foreach ( var i in mpKeys)
{
prefixSum = prefixSum + mp[i];
range.Add(i);
freq.Add(prefixSum);
}
foreach ( var p in q)
{
int idx = lower_bound(range, p);
if (idx >= 0 && idx < range.Count) {
if (range[idx] != p)
idx--;
if (idx >= 0)
result.Add(freq[idx]);
else
result.Add(0);
}
else {
result.Add(freq[range.Count - 1]);
}
}
return result;
}
public static void Main( string [] args)
{
int [, ] arr
= { { 1, 5 }, { 3, 6 }, { 5, 7 }, { 12, 15 } };
int [] q = { 1, 3, 5, 13 };
List< int > result = new List< int >();
findTheOccurrence(arr, q, result);
foreach ( var i in result) Console.Write(i + " " );
}
}
|
Javascript
function lower_bound(arr, ele)
{
for ( var i = 0; i < arr.length; i++)
{
if (arr[i] >= ele)
return i;
}
return arr.length - 1;
}
function findTheOccurrence(arr, q, result)
{
let n = arr.length;
let mp = {};
for ( var i of arr) {
if (!mp.hasOwnProperty(i[0]))
mp[i[0]] = 0;
if (!mp.hasOwnProperty(i[1] + 1))
mp[i[1] + 1] = 0;
mp[i[0]]++;
mp[i[1] + 1]--;
}
let range = [];
let freq = [];
let prefixSum = 0;
for (let [i, val] of Object.entries(mp)) {
prefixSum = prefixSum + val;
range.push(parseInt(i));
freq.push(prefixSum);
}
for ( var p of q) {
let idx = lower_bound(range, p);
if (idx >= 0 && idx < range.length) {
if (range[idx] != p)
idx--;
if (idx >= 0)
result.push(freq[idx]);
else
result.push(0);
}
else {
result.push(freq[range.length - 1]);
}
}
return result;
}
let arr = [[ 1, 5 ], [ 3, 6 ], [ 5, 7 ], [ 12, 15 ] ];
let q = [ 1, 3, 5, 13 ];
let result = [];
result = findTheOccurrence(arr, q, result);
for ( var i of result)
process.stdout.write(i + " " );
|
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...