Data Structures & AlgorithmsHard

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

  1. A. 8
  2. B. 11
  3. C. 36
  4. D. 21

Correct answer: D. 21

A sliding window with a count map gives the at-most-k count, but it must add right−left+1 per right end, not one per right end. The exactly-2 count and the at-most-3 count are different quantities and are common confusions.

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

Exams that ask this topic