Data Structures & AlgorithmsHardProduct Company SDE · Amazon OA

Problem: Count the subarrays of [2, 1, 3, 2, 1, 4, 2] that have exactly 2 distinct values.

  1. A. 13
  2. B. 6
  3. C. 21
  4. D. 5

Correct answer: B. 6

exactly(2) = atMost(2) − atMost(1) = 13 − 7 = 6: [2,1], [1,3], [3,2], [2,1], [1,4], [4,2]. Counting 'at most 2' gives 13, 'at least 2' gives 21, and counting distinct subarray contents merges the two [2,1] windows (5).

More Coding Interview Problems questions

Exams that ask this topic