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?- A. 13
- B. 6
- C. 7
- 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
- Find the bug: the code below should return the length of the longest substring without repeating characters. python def longest(s): last…
- Problem: Count the UNIQUE triplets (as value sets) that sum to zero, using sort + two pointers with duplicate skipping. python def…
- Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts). python def count(a…
- Search for a value in a sorted array that was rotated and MAY CONTAIN DUPLICATES (e.g. [1, 1, 1, 1, 0, 1, 1]). What is the worst-case time…
- Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n). python def peak(a)…
- Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and…