Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 nums between indices left and right (inclusive).
Example 1:
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.
Constraints:
1 <= arr.length <= 1051 <= arr[i], value <= 1040 <= left <= right < arr.length105 calls will be made to queryProblem summary: 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 nums between indices left and right (inclusive).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Binary Search · Design · Segment Tree
["RangeFreqQuery","query","query"] [[[12,33,4,56,22,2,34,33,22,12,34,56]],[1,2,4],[0,11,33]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2080: Range Frequency Queries
class RangeFreqQuery {
private Map<Integer, List<Integer>> g = new HashMap<>();
public RangeFreqQuery(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
g.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
}
public int query(int left, int right, int value) {
if (!g.containsKey(value)) {
return 0;
}
var idx = g.get(value);
int l = Collections.binarySearch(idx, left);
l = l < 0 ? -l - 1 : l;
int r = Collections.binarySearch(idx, right + 1);
r = r < 0 ? -r - 1 : r;
return r - l;
}
}
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* RangeFreqQuery obj = new RangeFreqQuery(arr);
* int param_1 = obj.query(left,right,value);
*/
// Accepted solution for LeetCode #2080: Range Frequency Queries
type RangeFreqQuery struct {
g map[int][]int
}
func Constructor(arr []int) RangeFreqQuery {
g := make(map[int][]int)
for i, v := range arr {
g[v] = append(g[v], i)
}
return RangeFreqQuery{g}
}
func (this *RangeFreqQuery) Query(left int, right int, value int) int {
if idx, ok := this.g[value]; ok {
l := sort.SearchInts(idx, left)
r := sort.SearchInts(idx, right+1)
return r - l
}
return 0
}
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* obj := Constructor(arr);
* param_1 := obj.Query(left,right,value);
*/
# Accepted solution for LeetCode #2080: Range Frequency Queries
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)
// Accepted solution for LeetCode #2080: Range Frequency Queries
use std::collections::HashMap;
struct RangeFreqQuery {
g: HashMap<i32, Vec<usize>>,
}
impl RangeFreqQuery {
fn new(arr: Vec<i32>) -> Self {
let mut g = HashMap::new();
for (i, &value) in arr.iter().enumerate() {
g.entry(value).or_insert_with(Vec::new).push(i);
}
RangeFreqQuery { g }
}
fn query(&self, left: i32, right: i32, value: i32) -> i32 {
if let Some(idx) = self.g.get(&value) {
let l = idx.partition_point(|&x| x < left as usize);
let r = idx.partition_point(|&x| x <= right as usize);
return (r - l) as i32;
}
0
}
}
// Accepted solution for LeetCode #2080: Range Frequency Queries
class RangeFreqQuery {
private g: Map<number, number[]> = new Map();
constructor(arr: number[]) {
for (let i = 0; i < arr.length; ++i) {
if (!this.g.has(arr[i])) {
this.g.set(arr[i], []);
}
this.g.get(arr[i])!.push(i);
}
}
query(left: number, right: number, value: number): number {
const idx = this.g.get(value);
if (!idx) {
return 0;
}
const l = _.sortedIndex(idx, left);
const r = _.sortedIndex(idx, right + 1);
return r - l;
}
}
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* var obj = new RangeFreqQuery(arr)
* var param_1 = obj.query(left,right,value)
*/
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.