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?- A. 12 5
- B. 12 7
- C. 15 7
- 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
- Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts. python def nice(a, k): cnt = {0: 1}…
- Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums). python from…
- Problem: Given n meetings with values, choose non-overlapping ones (end < next start) to maximise total value – weighted interval…
- Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or…
- Problem: Count the distinct BST shapes that store keys 1..n. python def shapes(n): dp = [1] + [0] n for k in range(1, n + 1): dp[k] =…
- Problem: Count the number of ways to tile a 2 × n board with 2 × 1 dominoes, modulo 10⁹ + 7. cpp const long long MOD = 1e9 + 7; long long…