Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties).

Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties).
from collections import Counter
def minwin(s, t):
    need, missing = Counter(t), len(t)
    l, best = 0, (0, float('inf'))
    for r, c in enumerate(s):
        if need[c] > 0: missing -= 1
        need[c] -= 1
        while missing == 0:
            if r - l < best[1] - best[0]: best = (l, r)
            need[s[l]] += 1
            if need[s[l]] > 0: missing += 1
            l += 1
    return s[best[0]:best[1] + 1]
print(minwin("baacbaab", "aab"))
What is printed?
  1. A. aab
  2. B. aacb
  3. C. cbaab
  4. D. baa

Correct answer: D. baa

t needs two a's and one b. The window shrinks whenever it is valid; 'baa' (indices 0–2) is the first length-3 window, and 'aab' at the end is also length 3, but the strict < keeps the leftmost. A window such as 'aacb' also has the letters but is longer.

More Coding Interview Problems questions

Exams that ask this topic