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))
  1. A. 16 7 9
  2. B. 13 8 5
  3. C. 16 8 8
  4. 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.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic