[LeetCode] Range Frequency Queries

2080. Range Frequency Queries

Design a data structure to find the frequency of a given value in a given subarray.

The frequency of a value in a subarray is the number of occurrences of that value in the subarray.

Implement the RangeFreqQuery class:

  • RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.
  • int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left…right].

A subarray is a contiguous sequence of elements within an array. arr[left…right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class RangeFreqQuery {
vector<int> _arr[10001] = {};
public:
RangeFreqQuery(vector<int>& arr) {
for(int i = 0; i < arr.size(); i++)
_arr[arr[i]].push_back(i);
}

int query(int left, int right, int value) {
return upper_bound(begin(_arr[value]), end(_arr[value]), right) - lower_bound(begin(_arr[value]), end(_arr[value]), left);
}
};

/**
* Your RangeFreqQuery object will be instantiated and called as such:
* RangeFreqQuery* obj = new RangeFreqQuery(arr);
* int param_1 = obj->query(left,right,value);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/02/PS/LeetCode/range-frequency-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.