ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
from collections import Counter
def mw(s, t):
    need = Counter(t)
    have = {}
    formed = 0
    req = len(need)
    l = 0
    best = (float('inf'), 0, 0)
    for r, ch in enumerate(s):
        have[ch] = have.get(ch, 0) + 1
        if ch in need and have[ch] == need[ch]:
            formed += 1
        while formed == req:
            if r - l + 1 < best[0]:
                best = (r - l + 1, l, r)
            c = s[l]
            have[c] -= 1
            if c in need and have[c] < need[c]:
                formed -= 1
            l += 1
    return s[best[1]:best[2] + 1] if best[0] != float('inf') else ''
print(mw('ADOBECODEBANC', 'ABC'), repr(mw('a', 'aa')))
  1. A. BANC ''
  2. B. ABC ''
  3. C. BANC a
  4. D. ADOBEC ''

Correct answer: A. BANC ''

The window expands to the right until every required letter is covered, then shrinks from the left while it stays valid. The shortest covering window is BANC, and when no window exists the function returns the empty string.

More Python Programming questions

Exams that ask this topic