76. Minimum Window Substring
Asked at 32Meta73Amazon62Microsoft55Bloomberg44Google42Lyft94Infosys54Wissen Technology100Snowflake92Snap92Harness89DP world88SoFi86Moloco81Adobe79Zeta74TikTok73Qualtrics69LinkedIn67Swiggy59Meesho57Uber57IBM55Walmart Labs53Oracle52Salesforce49Zoho42Anduril41Airbnb38Cisco37Yandex36Goldman Sachs33
Problem
Return the shortest substring of s that contains every character of t, duplicates included (two as in t need two as in the window). Return "" if there is none; the answer is unique when it exists.
Example: s = "ADOBECODEBANC", t = "ABC" → "BANC"
Constraints: lengths ≤ 10⁵. Follow-up: O(m + n).
Expand r until the window covers all of t (missing == 0), then shrink l as far as possible while still covering, recording the smallest window.
s = ADOBECODEBANC, t = ABC
[ADOBEC]ODEBANC covers -> shrink: drop A -> missing A
ADOBEC[ODEBA]NC ...
ADOBECODE[BANC] covers, len 4 <- answer "BANC"
Complexity: O(|s| + |t|).
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = Counter(t)
missing = len(t)
l = start = 0
best = float("inf")
for r, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0:
if r - l + 1 < best:
start, best = l, r - l + 1
need[s[l]] += 1
if need[s[l]] > 0:
missing += 1
l += 1
return "" if best == float("inf") else s[start:start + best]
assert Solution().minWindow("ADOBECODEBANC", "ABC") == "BANC"
assert Solution().minWindow("a", "aa") == ""
class Solution {
public String minWindow(String s, String t) {
int[] need = new int[128];
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(), l = 0, start = 0, best = Integer.MAX_VALUE;
for (int r = 0; r < s.length(); r++) {
if (need[s.charAt(r)]-- > 0) missing--;
while (missing == 0) {
if (r - l + 1 < best) { best = r - l + 1; start = l; }
if (++need[s.charAt(l++)] > 0) missing++;
}
}
return best == Integer.MAX_VALUE ? "" : s.substring(start, start + best);
}
}
func minWindow(s string, t string) string {
var need [128]int
for i := 0; i < len(t); i++ {
need[t[i]]++
}
missing, l, start, best := len(t), 0, 0, math.MaxInt
for r := 0; r < len(s); r++ {
if need[s[r]] > 0 {
missing--
}
need[s[r]]--
for missing == 0 { // window covers t: shrink it
if r-l+1 < best {
start, best = l, r-l+1
}
need[s[l]]++
if need[s[l]] > 0 {
missing++
}
l++
}
}
if best == math.MaxInt {
return ""
}
return s[start : start+best]
}