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

Problem: Find the minimum window length in which every one of k distinct product IDs appears at least once (k = number of distinct values in the array).

Problem: Find the minimum window length in which every one of k distinct product IDs appears at least once (k = number of distinct values in the array).
from collections import Counter
def min_all(a):
    need = len(set(a)); cnt = Counter(); have = l = 0; best = len(a)
    for r, x in enumerate(a):
        cnt[x] += 1; have += cnt[x] == 1
        while have == need:
            best = min(best, r - l + 1)
            cnt[a[l]] -= 1; have -= cnt[a[l]] == 0; l += 1
    return best
print(min_all([2, 1, 2, 3, 3, 1, 2]), min_all([5, 5, 5]))
What is printed?
  1. A. 4 1
  2. B. 3 3
  3. C. 3 1
  4. D. 2 1

Correct answer: C. 3 1

Expand until every distinct value is present (have == need), then shrink while it stays complete. The window [1, 2, 3] at indices 1..3 covers all three IDs; nothing shorter can. If the array has one distinct value, a single element suffices. Each pointer moves at most n times: O(n).

More Coding Interview Problems questions

Exams that ask this topic