#2080

Range Frequency Queries

Medium
ArrayHash TableBinary SearchDesignSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q log k)
Space
O(1)
O(n)
💡

Intuition

Time O(n + q log k)Space O(n)

By using a hashmap to store the indices of each value, we can quickly determine how many times a value appears in any subarray using binary search. This drastically reduces the time complexity for each query.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hashmap where keys are the values from the array and values are lists of indices where these values occur.
  2. 2Step 2: For each query, retrieve the list of indices for the target value.
  3. 3Step 3: Use binary search to find the count of indices that fall within the specified left and right bounds.
solution.py16 lines
1from collections import defaultdict
2import bisect
3
4class RangeFreqQuery:
5    def __init__(self, arr):
6        self.index_map = defaultdict(list)
7        for i, num in enumerate(arr):
8            self.index_map[num].append(i)
9
10    def query(self, left, right, value):
11        if value not in self.index_map:
12            return 0
13        indices = self.index_map[value]
14        left_index = bisect.bisect_left(indices, left)
15        right_index = bisect.bisect_right(indices, right)
16        return right_index - left_index

Complexity note: The time complexity is O(n) for preprocessing the array into a hashmap and O(log k) for each query, where k is the number of occurrences of the value. This is efficient for multiple queries.

  • 1Using a hashmap allows for quick access to indices, making queries efficient.
  • 2Binary search is a powerful tool for finding boundaries in sorted data.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.