Problem
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 arrayarr
.int query(int left, int right, int value)
Returns the frequency ofvalue
in the subarrayarr[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).
Examples
Example 1:
|
|
Solution
Method 1 - Using Map of List
To solve this problem, we can use a HashMap to preprocess and store the indices of all occurrences of each number in the array. This will allow us to efficiently query the frequency of a value in a given subarray using binary search.
Here are key points:
- Data Structure:
- Use a
HashMap<Integer, List<Integer>>
(ordefaultdict
in Python) to map each value in the array to its list of indices. - For example, for the array
[1, 2, 1, 3, 1]
, the map would look like:{1: [0, 2, 4], 2: [1], 3: [3]}
.
- Use a
- Preprocessing:
- Iterate through the array, and populate the map such that for each number, we store its list of indices.
- This step takes
O(n)
time, wheren
is the size of the array.
- Query Operation:
- To determine the number of occurrences of a value in
arr[left...right]
, use the precomputed indices from the HashMap. - Use binary search (via
Collections.binarySearch
in Java orbisect
in Python) to find:- The smallest index in the list that is
>= left
. - The largest index in the list that is
<= right
.
- The smallest index in the list that is
- The difference between these indices gives the frequency of the value in the subarray.
- To determine the number of occurrences of a value in
Code
|
|
|
|
Complexity
- ⏰ Time complexity
- Preprocessing:
O(n)
- Query:
- Binary searches (
O(log k)
each) to locate the range of indices, wherek
is the total number of occurrences of the value in the array. - Hence, query complexity is
O(log k)
.
- Binary searches (
- Preprocessing:
- 🧺 Space complexity:
O(n)