Data Structures & AlgorithmsVery hardProduct company OA

Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed?

Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed?
from collections import Counter
def min_window(s, t):
    need, have, missing = Counter(t), {}, len(t)
    lo, best = 0, (10**9, 0, 0)
    for hi, ch in enumerate(s):
        if need[ch] > 0: missing -= 1
        need[ch] -= 1
        if missing == 0:
            while need[s[lo]] < 0: need[s[lo]] += 1; lo += 1
            best = min(best, (hi - lo + 1, lo, hi))
            need[s[lo]] += 1; missing += 1; lo += 1
    return s[best[1]:best[2] + 1] if best[0] < 10**9 else ""
print(min_window("cabwefgewcwaefgcf", "cae"), min_window("aabbaac", "aab"), repr(min_window("ab", "aa")))
  1. A. cwae aab 'ab'
  2. B. cwae aab ''
  3. C. aefgc aab ''
  4. D. cwae aabb ''

Correct answer: B. cwae aab ''

need[c] > 0 means c is still missing; once missing hits 0 the left edge is advanced past surplus characters (need < 0), the window is recorded, and then one required character is released to look for a later window. 'cwae' (indices 9–12) is the shortest window with c, a, e. For aab the first three letters already work. t = 'aa' needs two a's but 'ab' has one, so the answer is empty. O(|s| + |t|).

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

Exams that ask this topic