Range Frequency Queries - 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 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 arr between indices left and right (inclusive).

Input & Output

Example 1 — Basic Range Query
$ Input: arr = [1,2,2,3,1], operations = [[0,4,1],[1,3,2]]
Output: [2,2]
💡 Note: For query [0,4,1]: value 1 appears at indices 0 and 4, both in range → count = 2. For query [1,3,2]: value 2 appears at indices 1 and 2, both in range → count = 2.
Example 2 — Value Not in Range
$ Input: arr = [1,1,1,1], operations = [[1,2,2]]
Output: [0]
💡 Note: Query [1,2,2]: looking for value 2 in range [1,2], but value 2 doesn't exist in the array → count = 0.
Example 3 — Single Element Range
$ Input: arr = [5,3,5,1,5], operations = [[0,0,5],[2,2,5]]
Output: [1,1]
💡 Note: Query [0,0,5]: range contains only index 0 with value 5 → count = 1. Query [2,2,5]: range contains only index 2 with value 5 → count = 1.

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ value ≤ 104
  • 0 ≤ left ≤ right < arr.length
  • At most 105 calls to query

Visualization

Tap to expand
Range Frequency Queries INPUT arr = [1, 2, 2, 3, 1] 1 i=0 2 i=1 2 i=2 3 i=3 1 i=4 Operations: query(0, 4, 1) -- count 1s query(1, 3, 2) -- count 2s Data Structure: HashMap<value, indices> 1 --> [0, 4] 2 --> [1, 2] 3 --> [3] ALGORITHM STEPS 1 Build Hash Map Store indices for each value 2 Get Index List Retrieve sorted indices for value 3 Binary Search Find bounds in range [L,R] 4 Count Frequency rightBound - leftBound Query 1: query(0, 4, 1) indices[1] = [0, 4] Both 0,4 in range [0,4] Result: 2 Query 2: query(1, 3, 2) indices[2] = [1, 2] Both 1,2 in range [1,3] Result: 2 FINAL RESULT Output Array: [2, 2] Query Results: query(0,4,1) = 2 Value 1 appears 2 times query(1,3,2) = 2 Value 2 appears 2 times Complexity: Build: O(n) Query: O(log n) Key Insight: By storing sorted indices for each unique value in a HashMap, we can efficiently answer range frequency queries using binary search. The lower_bound and upper_bound positions in the index list directly give us the count of occurrences within the query range [L, R]. TutorialsPoint - Range Frequency Queries | Hash Map with Index Lists
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen