Data Structures & AlgorithmsVery hardProduct company OA
atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed?
at_most(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed?
def at_most(s, k):
cnt, lo, total = {}, 0, 0
for hi, ch in enumerate(s):
cnt[ch] = cnt.get(ch, 0) + 1
while len(cnt) > k:
cnt[s[lo]] -= 1
if cnt[s[lo]] == 0: del cnt[s[lo]]
lo += 1
total += hi - lo + 1
return total
s = "abcabba"
print(at_most(s, 2), at_most(s, 1), at_most(s, 2) - at_most(s, 1))- A. 16 7 9
- B. 13 8 5
- C. 16 8 8
- D. 28 8 20
Correct answer: C. 16 8 8
For each right end hi the window [lo, hi] is the longest valid one ending at hi, and every shorter suffix of it is valid too, so it contributes hi − lo + 1 substrings. at_most(2) = 1+2+2+2+2+3+4 = 16 and at_most(1) = 1+1+1+1+1+2+1 = 8 (the runs 'bb' add an extra). 'Exactly k distinct' is not monotone under shrinking, so it is computed as at_most(k) − at_most(k − 1) = 8. 28 is the total number of substrings.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…
- Largest rectangle under a histogram using a stack of (start index, height). What is printed? python def rect(h): st, best = [], 0 for i, x…
- Rain water trapped between bars, computed with two pointers. What is printed? python def water(h): l, r, lm, rm, w = 0, len(h) - 1, 0, 0…