Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the smallest window of s that contains every character of t (with multiplicity).
Problem: Return the smallest window of s that contains every character of t (with multiplicity).
from collections import Counter
def min_window(s, t):
need, missing = Counter(t), len(t)
l = 0; best = (0, float('inf'))
for r, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 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 "" if best[1] == float('inf') else s[best[0]:best[1] + 1]
print(min_window("XAYBZAXB", "ABX"))What is printed?- A. XAYB
- B. BZAX
- C. AXB
- D. ZAXB
Correct answer: C. AXB
Expand until every needed letter is covered (missing = 0), then shrink from the left while it stays covered. The first valid window is XAYB (length 4), later BZAX (length 4), and finally AXB at indices 5..7 (length 3), the shortest. Each pointer moves at most n times: O(|s| + |t|). Returning the first valid window (XAYB) is the usual mistake.
More Coding Interview Problems questions
- Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case…
- Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one). python def almost(s): def…
- Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1). python…
- Problem: Reverse the order of words in a sentence, collapsing multiple spaces. python s = " the sky is blue " print("|" + "…
- Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1. java static int…
- Problem: Check whether s2 contains a permutation of s1 as a substring. python def hasperm(s1, s2): k = len(s1) need = [0] 26; win = [0] 26…