Problem overview
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 a's, the substring needs at least two. When no substring works, the function returns the empty string. Uppercase and lowercase letters are different characters.
For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". For "a" and "a" it is "a". For "a" and "aa" it is "", because s has only one a.
The statement asks for O(n + m) time and O(1) extra space, with n the length of s and m the length of t.
Approach
Checking every substring of s against t is far too slow. A sliding window does it in one pass. Move the right end of the window forward one character at a time until the window holds everything t needs. Then move the left end forward while the window stays complete, to make it as short as possible, and remember it if it is the shortest so far. Then the right end continues.
To know whether the window is complete without recounting, the code keeps one array, need, indexed by character code. need[code] is how many more of that character the window still needs. A new character entering the window lowers its entry by one. A positive entry means the window is short of that character, zero means it has exactly enough, and a negative entry means it holds spare copies. A second number, missing, counts how many characters of t the window still lacks, so the window is complete exactly when missing is 0.
Step by step
- Create
need, anIntArray(128). Letters have codes below 128, so one entry per code covers a to z and A to Z, each case separately. - Count the characters of
t. Loopingfor (c in t)and adding 1 toneed[c.code]records how many copies of each letter the window must hold.c.codeis the character's code as anInt. - Set
missingtot.length. Before the window holds anything, it lacks every character oft. - Create
first,bestStartandbestLength.firstis the left end of the window.bestLengthstarts ats.length + 1, a value no real window can have, which means no complete window has been found yet. - Loop
lastovers.indices, adding the character atlastto the window. Read its code intocode. - Update the counts. If
need[code]is above 0, the window really needed this character, somissinggoes down. If it is 0 or negative, the character is an extra copy andmissingstays. In both casesneed[code]then goes down by one. - When
missing == 0, the window is complete. Movefirstright whileneed[s[first].code] < 0: a negative entry means the window has more of that character thantasks for, so dropping the character keeps the window complete. Each drop adds 1 back to its entry. - Compare lengths. If
last - first + 1is smaller thanbestLength, rememberfirstand the new length. Only the start and the length are stored, so the substring is cut once, at the end. - After the loop, if
bestLengthis still aboves.length, no window was ever complete, so return"". Otherwise return the substring frombestStartup tobestStart + bestLength.
The solution in Kotlin
class Solution {
fun minWindow(s: String, t: String): String {
val need = IntArray(128)
for (c in t) {
need[c.code]++
}
var missing = t.length
var first = 0
var bestStart = 0
var bestLength = s.length + 1
for (last in s.indices) {
val code = s[last].code
if (need[code] > 0) missing--
need[code]--
if (missing == 0) {
while (need[s[first].code] < 0) {
need[s[first].code]++
first++
}
if (last - first + 1 < bestLength) {
bestStart = first
bestLength = last - first + 1
}
}
}
if (bestLength > s.length) return ""
return s.substring(bestStart, bestStart + bestLength)
}
}
Some Kotlin details in this code:
c.codeturns aCharinto its numeric code. For example'a'.codeis 97 and'A'.codeis 65.if (need[code] > 0) missing--is a one-lineifwithout braces. Kotlin allows that for a single statement.substring(i, j)includes indexiand excludes indexj, hencebestStart + bestLengthas the end.need[code]--works on an array element directly. A newIntArrayis filled with zeros.
Tracing the example
This is the state after each character of s = "ADOBECODEBANC" with t = "ABC":
last=0 A missing=2 first=0 best=none
last=1 D missing=2 first=0 best=none
last=2 O missing=2 first=0 best=none
last=3 B missing=1 first=0 best=none
last=4 E missing=1 first=0 best=none
last=5 C missing=0 first=0 best=ADOBEC
last=6 O missing=0 first=0 best=ADOBEC
last=7 D missing=0 first=0 best=ADOBEC
last=8 E missing=0 first=0 best=ADOBEC
last=9 B missing=0 first=0 best=ADOBEC
last=10 A missing=0 first=5 best=ADOBEC
last=11 N missing=0 first=5 best=ADOBEC
last=12 C missing=0 first=9 best=BANC
The window first becomes complete at index 5 (ADOBEC). At index 10 the second A arrives, which lets the left end jump from 0 to 5, giving CODEBA, no shorter than the best. At index 12 the last C arrives and the left end moves to 9, giving BANC with length 4.
Complexity
Time: O(n + m). Counting t takes m steps. After that last visits each index of s once, and first only moves right, so the inner while runs at most n times in total.
Space: O(1). The need array has 128 entries whatever the input.
Edge cases and common mistakes
- Repeated characters in
t."aab"witht = "aab"returns"aab": the count inneedis 2 fora, so a window with oneais not complete. - No valid window.
"a"witht = "aa"returns"". - Case matters.
"Ab"witht = "ab"returns"", becauseAandahave different codes. - Extra copies. In
"abcabc"witht = "cba"the answer is"abc", the first window that is complete. Later windows of the same length don't replace it, because the comparison is strict (<). - Counting only distinct characters. Using a set instead of counts would accept a window with one
awhentneeds two. - Using the window length as the answer. The function returns the substring, not its length, and uses
""when nothing was found.
Testing
"ADOBECODEBANC" "ABC" -> "BANC"
"a" "a" -> "a"
"a" "aa" -> ""
"aab" "aab" -> "aab"
"abcabc" "cba" -> "abc"
"Ab" "ab" -> ""
"aaflslflsldkalskaaa" "aaa" -> "aaa"
