Data Structures & AlgorithmsHard

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

  1. A. 10
  2. B. 18
  3. C. 7
  4. D. 17

Correct answer: A. 10

Exactly k distinct values equals at-most-k minus at-most-(k−1). The mix of 2 and 3 distinct values in the last option is a classic off-by-one error with the difference trick.

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

Exams that ask this topic