Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values.

Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values.
from collections import defaultdict
def at_most(a, k):
    cnt = defaultdict(int); l = res = 0
    for r, x in enumerate(a):
        if cnt[x] == 0: k -= 1
        cnt[x] += 1
        while k < 0:
            cnt[a[l]] -= 1
            if cnt[a[l]] == 0: k += 1
            l += 1
        res += r - l + 1
    return res
a = [1, 2, 1, 2, 3]
print(at_most(a, 2), at_most(a, 2) - at_most(a, 1))
What is printed?
  1. A. 12 5
  2. B. 12 7
  3. C. 15 7
  4. D. 11 7

Correct answer: B. 12 7

Every right end r adds r − l + 1 valid windows. at_most(2) = 1 + 2 + 3 + 4 + 2 = 12 and at_most(1) = 5 (single elements), so exactly 2 distinct = 12 − 5 = 7. Counting 'exactly k' directly with one window fails because shrinking can skip valid starts. O(n).

More Coding Interview Problems questions

Exams that ask this topic