Range Frequency Queries — LeetCode 2080 Python Solution
MediumDesignSegment TreeArrayHash TableBinary Search
- Problem
- #2080
- Pattern
- Binary Search
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["RangeFreqQuery", "query", "query"]
- Output
- [null, 1, 2]
- Explanation
- RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);
Python solution
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 2080. Range Frequency Queries is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2080. Range Frequency Queries?
- LeetCode 2080. Range Frequency Queries is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2080. Range Frequency Queries?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2080. Range Frequency Queries?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2080. Range Frequency Queries cover?
- LeetCode 2080. Range Frequency Queries is tagged Design, Segment Tree, Array, Hash Table and Binary Search on LeetCode.