Data Structures & AlgorithmsHardGATE CS · Amazon SDE round

How many contiguous subarrays of [1, 2, 1, 2, 3, 3, 4] contain at most 2 distinct values?

  1. A. 16
  2. B. 19
  3. C. 18
  4. D. 21

Correct answer: C. 18

Count with a sliding window: for each right end, the number of valid left ends is added in one step. Forgetting that a shorter subarray is counted in every longer valid one is the usual slip.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic