Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count subarrays with EXACTLY k distinct values using exactly(k) = atMost(k) − atMost(k − 1).

Problem: Count subarrays with EXACTLY k distinct values using exactly(k) = atMost(k) − atMost(k − 1).
def at_most(a, k):
    cnt, l, res = {}, 0, 0
    for r, x in enumerate(a):
        cnt[x] = cnt.get(x, 0) + 1
        while len(cnt) > k:
            cnt[a[l]] -= 1
            if cnt[a[l]] == 0: del cnt[a[l]]
            l += 1
        res += r - l + 1
    return res
a = [1, 2, 1, 3, 2, 3]
print(at_most(a, 2) - at_most(a, 1))
What is printed?
  1. A. 13
  2. B. 6
  3. C. 7
  4. D. 11

Correct answer: C. 7

atMost(2) counts 13 subarrays with ≤ 2 distinct values and atMost(1) counts the 6 single-element subarrays (no two equal neighbours), so exactly-2 = 13 − 6 = 7. A plain sliding window cannot count 'exactly k' directly because the valid left boundaries form a range, not a single point.

More Coding Interview Problems questions

Exams that ask this topic