Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

Array a = [1, 2, 1, 3, 2, 2, 4, 1]. What is the length of the longest contiguous subarray that contains at most two distinct values?

  1. A. 4
  2. B. 1
  3. C. 5
  4. D. 3

Correct answer: D. 3

A sliding window keeps a count of each value inside it and shrinks from the left whenever more than two distinct values appear. The window never needs to move backwards, so the scan is linear.

More Coding Interview Problems questions

Exams that ask this topic