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?

  1. A. O(n·k) – rebuild a set per window
  2. B. O(n) – slide a window with a hash map of counts; add the entering value and remove the leaving value
  3. C. O(n log n) – sort each window
  4. 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

Exams that ask this topic