ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def most2(s):
    cnt = {}
    l = best = 0
    for r, ch in enumerate(s):
        cnt[ch] = cnt.get(ch, 0) + 1
        while len(cnt) > 2:
            cnt[s[l]] -= 1
            if cnt[s[l]] == 0:
                del cnt[s[l]]
            l += 1
        best = max(best, r - l + 1)
    return best
print(most2('eceba'), most2('ccaabbb'))
  1. A. 2 5
  2. B. 3 4
  3. C. 4 5
  4. D. 3 5

Correct answer: D. 3 5

A sliding window keeps at most two distinct characters and shrinks from the left when a third appears. ece has length 3 and aabbb has length 5.

More Python Programming questions

Exams that ask this topic