Data Structures & AlgorithmsVery hard

Which statement about counting subarrays with EXACTLY k distinct values is correct?

  1. A. exactly(k) = atMost(k) − atMost(k+2)
  2. B. exactly(k) = atMost(k) − atMost(k−1)
  3. C. exactly(k) = atMost(k)
  4. D. exactly(k) = atMost(k−1) + atMost(k)

Correct answer: B. exactly(k) = atMost(k) − atMost(k−1)

Every subarray with at most k distinct values either has exactly k or at most k−1. Subtracting the at-most-(k−1) count from the at-most-k count leaves exactly the subarrays with k distinct values.

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

Exams that ask this topic