Leetcode #2080: Range Frequency Queries
In this guide, we solve Leetcode #2080 Range Frequency Queries in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Design, Segment Tree, Array, Hash Table, Binary Search
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input
["RangeFreqQuery", "query", "query"]
[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]
Output
[null, 1, 2]
Explanation
RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);
rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]
rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.
Python Solution
class RangeFreqQuery:
def __init__(self, arr: List[int]):
self.g = defaultdict(list)
for i, x in enumerate(arr):
self.g[x].append(i)
def query(self, left: int, right: int, value: int) -> int:
idx = self.g[value]
l = bisect_left(idx, left)
r = bisect_left(idx, right + 1)
return r - l
# Your RangeFreqQuery object will be instantiated and called as such:
# obj = RangeFreqQuery(arr)
# param_1 = obj.query(left,right,value)
Complexity
The time complexity is O(n). The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.