Problem overview
The function min_window receives two strings, s and t, made of English letters. It returns the shortest substring of s that contains every character of t, repeats included: if t has two a's, the substring needs at least two. When no substring works, it returns an empty string. Uppercase and lowercase letters are different characters, and the tests are built so that the answer is unique.
For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". "ADOBEC" and "CODEBA" also contain an A, a B and a C, but they are longer. For s = "a" and t = "a" the answer is "a", and for s = "a" and t = "aa" it is "", because s has only one a.
Approach: grow the window, then trim it
Checking every substring of s against t would be far too slow for strings of 100,000 characters. A sliding window does it in one pass. The window is the substring from index first to index last:
lastmoves right one character at a time, adding to the window.- As soon as the window holds everything
tneeds,firstmoves right while the window can spare its first character, which makes it as short as possible for thislast. - If the trimmed window is shorter than the best so far, remember where it starts and how long it is.
Both ends only move right, so the time is O(n + m) for n = s.len() and m = t.len(). The extra space is one counter for each of the 128 ASCII codes, which is O(1).
One counter per character
The array need records how many more of each character the window still needs. It starts as the character counts of t. Adding a character to the window subtracts 1 from its count. So:
- A count above 0 means the window still lacks some of that character.
- A count of exactly 0 means the window has exactly as many as
tasks for. - A count below 0 means the window holds extras, and the first of them can leave without breaking the window.
A separate number, missing, starts as t.len() and drops by 1 only when a character that was still needed enters the window. When missing is 0, the window is complete, and checking that is a single comparison.
Tracing s = "ADOBECODEBANC" with t = "ABC":
| last | char | missing | window after trimming | best so far |
|---|---|---|---|---|
| 0 | A | 2 | A | none |
| 3 | B | 1 | ADOB | none |
| 5 | C | 0 | ADOBEC | ADOBEC |
| 9 | B | 0 | ADOBECODEB | ADOBEC |
| 10 | A | 0 | CODEBA | ADOBEC |
| 12 | C | 0 | BANC | BANC |
The window first becomes complete at index 5. At index 10 the new A lets the left end skip A, D, O, B and E, which leaves CODEBA, with length 6, so it doesn't beat ADOBEC. At index 12, the window trims down to BANC, with length 4.
Step by step
- Get the bytes of
swithas_bytes(), so characters can be read by index. - Create
needas[0i32; 128]. Letters have codes below 128, so uppercase and lowercase each get their own entry. - Count
t. Loopcovert.bytes()and add 1 toneed[c as usize]. A letter that appears twice is needed twice. - Set
missingtot.len(): how many characters the window still lacks. - Prepare the best window.
firstandbest_startstart at 0, andbest_lengthstarts atbytes.len() + 1. No window can be that long, so this value means that none has been found. - Loop
lastover0..bytes.len()and store the character's code incode. - Update
missing. Ifneed[code]is above 0, the window needed this character, so subtract 1 frommissing. Then subtract 1 fromneed[code]in every case. - When
missing == 0, trim from the left. Whileneed[bytes[first] as usize] < 0, the window has an extra of its first character: give it back by adding 1 to its count and movingfirstright. - Compare lengths. If
last - first + 1 < best_length, savefirstasbest_startand the length asbest_length. Only the position and length are stored; the substring is cut once, at the end. - No window found. After the loop, if
best_lengthis still abovebytes.len(), returnString::new(). - Return the best window as a new
String, with no semicolon.
The solution in Rust
impl Solution {
fn min_window(s: String, t: String) -> String {
let bytes = s.as_bytes();
let mut need = [0i32; 128];
for c in t.bytes() {
need[c as usize] += 1;
}
let mut missing = t.len();
let mut first = 0usize;
let mut best_start = 0usize;
let mut best_length = bytes.len() + 1;
for last in 0..bytes.len() {
let code = bytes[last] as usize;
if need[code] > 0 {
missing -= 1;
}
need[code] -= 1;
if missing == 0 {
while need[bytes[first] as usize] < 0 {
need[bytes[first] as usize] += 1;
first += 1;
}
if last - first + 1 < best_length {
best_start = first;
best_length = last - first + 1;
}
}
}
if best_length > bytes.len() {
return String::new();
}
s[best_start..best_start + best_length].to_string()
}
}
The Rust details worth a closer look:
t.bytes()is an iterator ofu8values. Au8can't index an array directly, soc as usizeconverts it.- Two integer types.
needholdsi32values because it must go below zero.missingis ausizebecause it starts ast.len()and only reaches 0 when the window is complete. It never goes below 0, because it only drops whenneed[code]is positive. - Slicing a string.
s[a..b]takes a byte range of theStringand gives astr, andto_string()copies it into a newString. Rust panics if a range ends in the middle of a multi-byte character. With letters only, each character is one byte, so this can't happen. - Letters only.
need[code]panics with an out-of-bounds index for a code of 128 or more, such as a character outside ASCII. The constraints guarantee English letters. - Early
return.return String::new();leaves the function at once. The final line has no semicolon, so it is the value the function returns otherwise. - Why
firststays in range. Inside thewhile, the window is complete, so a character with a negative count really is in it. The loop therefore stops at or beforelast.
Complexity
Time: O(n + m). Counting t takes m steps. After that, last moves n times and first moves at most n times in total, each step costing a constant amount.
Space: O(1) extra. The array has 128 entries, whatever the input. The returned string is a copy of the answer.
Edge cases and common mistakes
- No valid window.
s = "a"witht = "aa"returns"", and so doess = "Ab"witht = "aB", because uppercase and lowercase letters are different. - Repeated characters in
t. Withs = "aaflslflsldkalskaaa"andt = "aaa"the answer is"aaa". Treatingtas a set of letters instead of counts would accept a window with a singlea. - The whole string. If
sequalstup to order, as in"abc"and"cba", the answer is all ofs. - Characters not in
t. They have a count of 0, so adding one drops it to -1, and it is trimmed from the left when it reaches the front. It never changesmissing. - Counting extras as progress. Subtracting 1 from
missingwithout checkingneed[code] > 0would count a thirdatoward atthat asks for two. - Trimming before the window is complete. The trim only runs when
missing == 0. Before then, characters at the front are still needed.
Testing
s = "ADOBECODEBANC",t = "ABC"gives"BANC".s = "a",t = "a"gives"a".s = "a",t = "aa"gives"".s = "aab",t = "ab"gives"ab".s = "ab",t = "b"gives"b".s = "Ab",t = "aB"gives"".
