Data Structures & AlgorithmsVery hardCodeforces Div2 D · LeetCode-style

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

  1. A. 9
  2. B. 18
  3. C. 12
  4. D. 10

Correct answer: A. 9

Use exactly(k) = atMost(k) − atMost(k − 1), where atMost is counted with a sliding window that tracks the number of distinct values. Counting windows with at most k distinct values answers a different question.

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

Exams that ask this topic