Problem Description
Design a data structure that supports counting the frequency of a given integer value within any subarray of a provided array. The data structure must support efficient queries after an initial preprocessing step.
Key Insights
- Preprocessing is essential since there can be up to 10^5 queries.
- Use a hash map (or dictionary) to map each distinct value to a sorted list of indices where it appears.
- Use binary search to quickly count how many indices fall within a given range for a queried value.
- The approach ensures that each query is processed in logarithmic time relative to the number of occurrences of the value.
Space and Time Complexity
Time Complexity:
- Preprocessing: O(n), where n is the length of the array.
- Each query: O(log k), where k is the number of occurrences of the queried value.
Space Complexity:
- O(n) for storing the indices of each occurrence in the hash map.
Solution
We first build a hash map where the key is the array's value and the corresponding value is a list of sorted indices at which it appears. When a query is performed with a range [left, right] and a target value, we retrieve the sorted list of indices for that value. Using binary search, we can determine:
- The first occurrence index in the list that is not less than left.
- The first occurrence index in the list that is greater than right. The difference between these two positions gives the count of indices in the range.
The solution leverages sorting, binary search, and hash maps to provide efficient range frequency queries.