Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE
Problem: Count distinct values in every window of size k over n = 10⁶ values. What is the optimal complexity?
- A. O(n·k) – rebuild a set per window
- B. O(n) – slide a window with a hash map of counts; add the entering value and remove the leaving value
- C. O(n log n) – sort each window
- D. O(n√n) – Mo's algorithm is needed
Correct answer: B. O(n) – slide a window with a hash map of counts; add the entering value and remove the leaving value
Each step changes one count up and one down; the number of keys with count > 0 is maintained in O(1). Mo's algorithm handles arbitrary offline ranges, which is unnecessary for contiguous fixed windows.
More Coding Interview Problems questions
- Problem: n = 10⁵ cities connected by roads that are added one at a time; after each addition report the number of connected components…
- Problem: Find the longest substring that appears at least twice in a string of length 10⁵. Which approach is efficient?
- Problem: A recursive solution for 'number of ways to partition n into parts' is memoised on (n, largest part allowed). With n ≤ 1000, how…
- Problem: A function has T(n) = T(n − 1) + T(n − 2) + O(1) without memoisation. What is its growth?
- Problem: Dijkstra is run with a binary heap but WITHOUT the 'skip stale entry' check (if d > dist[u]: continue). What happens?
- Problem: n ≤ 10⁵ points on a line; answer 'how many points lie in [l, r]?' for 10⁵ queries. What is the simplest efficient solution?