Problem overview
The method minWindow receives two strings, s and t. It returns the shortest substring of s that contains every character of t, repeats included: if t has two as, the substring needs at least two. If no substring works, it returns "". 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". The substrings "ADOBEC" and "CODEBA" also hold an A, a B and a C, but they are longer. For s = "a" and t = "aa" the answer is "": t needs two as and s has only one.
Approach: grow the window, then trim it
Checking every substring of s against t is far too slow for 100,000 characters. A sliding window does it in one pass. The window is the substring from index first to index last.
- Move
lastto the right, adding one character to the window at a time. - Once the window holds everything
tasks for, it is complete. Movefirstto the right while the window can spare its first character, which makes it as short as possible for thislast. - Compare that length with the best found so far.
To know whether the window is complete without recounting it, keep a list need with one slot per character code. need[code] says how many more copies of that character the window still needs. It starts as the counts of t. Adding a character to the window lowers its slot by 1, and removing one raises it by 1. A slot at 0 means the window holds exactly the copies t asks for. A negative slot means it holds extras, which can leave without breaking the window.
The variable missing tracks how many characters of t are still lacking, counting repeats. It starts at len(t). When a character enters the window while its slot is above 0, it fills a real need, so missing drops by 1. When missing reaches 0, the window is complete.
Here is the run on "ADOBECODEBANC" with t = "ABC":
last=0 A missing=2
last=1 D missing=2
last=2 O missing=2
last=3 B missing=1
last=4 E missing=1
last=5 C missing=0 window "ADOBEC" best "ADOBEC"
last=6 O missing=0 window "ADOBECO" best "ADOBEC"
last=7 D missing=0 window "ADOBECOD" best "ADOBEC"
last=8 E missing=0 window "ADOBECODE" best "ADOBEC"
last=9 B missing=0 window "ADOBECODEB" best "ADOBEC"
last=10 A missing=0 window "CODEBA" best "ADOBEC"
last=11 N missing=0 window "CODEBAN" best "ADOBEC"
last=12 C missing=0 window "BANC" best "BANC"
At last=10 the new A makes the first A spare, so the trim drops A, D, O and B and stops at C, which is still needed. At last=12 the trim reaches "BANC", shorter than the best so far.
Step by step
- Create
needas[0] * 128. Letters have character codes below 128, so one slot per code coversatozandAtoZ, each case separately. - Loop over the characters of
tand add 1 toneed[ord(c)]. A letter that appears twice intis needed twice. - Set
missingtolen(t). - Set
first = bestStart = 0: the window's left end and the start of the best window so far. - Set
bestLengthtolen(s) + 1. No window can be that long, so this value means that none has been found yet. - Loop
lastoverrange(len(s)), adding the character atlastto the window. - Take its code with
ord(s[last]). - If
need[code]is above 0, subtract 1 frommissing. A slot at 0 or below means the window already has every copytasks for, so this one is extra. - Subtract 1 from
need[code]in every case, because the window now holds one more of that character. - Check
missing == 0. Only a complete window can be an answer. - Trim from the left with a
whileloop that runs whileneed[ord(s[first])]is below 0, which means the first character is spare. - Drop the first character: add 1 back to its slot and move
firstforward. - Compare lengths. If
last - first + 1is less thanbestLength, this is the shortest complete window so far. - Remember it by saving
bestStartandbestLength. Only the position and length are stored, and the substring is cut once at the end. - If
bestLengthis still abovelen(s), no window was ever complete, so return"". - Otherwise return the slice
s[bestStart:bestStart + bestLength].
The solution in Python
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = [0] * 128
for c in t:
need[ord(c)] += 1
missing = len(t)
first = bestStart = 0
bestLength = len(s) + 1
for last in range(len(s)):
code = ord(s[last])
if need[code] > 0:
missing -= 1
need[code] -= 1
if missing == 0:
while need[ord(s[first])] < 0:
need[ord(s[first])] += 1
first += 1
if last - first + 1 < bestLength:
bestStart = first
bestLength = last - first + 1
if bestLength > len(s):
return ""
return s[bestStart:bestStart + bestLength]
Python details worth a closer look:
- Iterating a string.
for c in tyields one-character strings, andord(c)turns each into its integer code. For example,ord('A')is 65 andord('a')is 97, which is why the two cases never share a slot. - Slices.
s[i:j]holds the characters from indexiup to but not includingj. Strings are immutable, so a slice makes a new string, and this code makes exactly one, at the end. - A negative slot is meaningful. Indexing a list with a negative index counts from the end, but here the negative numbers are the values in
need, so there is no wrap-around problem. The indices are always character codes, which are never negative. - Letters only. A character with a code of 128 or more would be out of range for
needand raiseIndexError. The constraints promise only English letters.
Complexity
Time: O(n + m) for n = len(s) and m = len(t). Counting t takes m steps. After that, last visits each index of s once, and first only moves right, so the trimming loop runs at most n times over the whole run.
Space: O(1). The list has 128 slots whatever the input length. The returned slice is the answer and not extra working space.
Edge cases and common mistakes
- Repeated letters in
t.s = "a"witht = "aa"returns"", ands = "aa"witht = "aa"returns"aa". A set of the letters intwould accept both. - Case matters.
s = "Ab"witht = "a"returns"", becauseAandaare different characters. tlonger thans.s = "ab"witht = "abc"returns"", sincemissingnever reaches 0.- Order doesn't matter.
s = "abc"witht = "cba"returns"abc". Only counts count. - Decrementing
missingfor extras. Ifmissingdropped for every character intregardless of the slot, a thirdawould be counted as progress and the window would look complete too early. Theneed[code] > 0test prevents that. - Trimming an incomplete window. The trim only runs when
missing == 0. Otherwise it could drop a character the window still needs. - Using
bestLength = len(s)as the starting value. Then a window equal to the whole string could never be recorded as an improvement, and the function would return""fors = "a"andt = "a". That is why the start islen(s) + 1.
Testing
s = "ADOBECODEBANC",t = "ABC"gives"BANC".s = "a",t = "a"gives"a".s = "a",t = "aa"gives"".s = "aa",t = "aa"gives"aa".s = "ab",t = "b"gives"b".s = "Ab",t = "a"gives"".s = "abc",t = "cba"gives"abc".s = "ab",t = "abc"gives"".
