Data Structures & AlgorithmsModerateAmazon · Microsoft OA

For an array of n = 10⁶ integers, report the number of DISTINCT values in every window of k = 10⁵ consecutive elements. Which approach is efficient and correct?

  1. A. Slide one window with a hash map of counts and a distinct counter, O(n)
  2. B. Put each window into a set from scratch, O(n · k)
  3. C. Sort each window and count runs, O(n · k log k)
  4. D. Use prefix sums of the values, O(n)

Correct answer: A. Slide one window with a hash map of counts and a distinct counter, O(n)

Each step changes only two counts, so the distinct total updates in O(1) average time: about 10⁶ operations. Rebuilding a set per window is 10¹¹ steps. Prefix sums add values; they cannot count distinct ones.

More Coding Interview Problems questions

Exams that ask this topic