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?- A. 4 1
- B. 3 3
- C. 3 1
- 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
- Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally). python def steps(n)…
- Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS). python from collections import deque…
- Problem: Count the inversions of an array with merge sort. python def inv(a): if len(a) < 2: return a, 0 m = len(a) // 2 L, x =…
- Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed). python def…
- Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed). cpp int n = 8; vector<long long> t(n + 1, 0); void…
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…