ntree.ai
ntree.aiMinimum Window Substring

Solutions

1. Brute Force

O(n²) time | O(m) space, for t of length m

Intuition

We can check every possible substring and keep the shortest one that contains every character of t.

For that we create a hash map with how many times each character appears in t, and subtract from it every time a character is in the substring.

Algorithm

  1. Create an empty string for the answer.
  2. Iterate through the outer loop from the first character to the last character with i index.
  3. For each outer loop iteration, create a hash map with how many times each character appears in t, a missing integer variable with the length of t, and iterate through the inner loop from the character at i to the last character with j index.
    • When the hash map has a key for the character at j with a value above 0, subtract one from that value and decrease missing by one.
    • When missing is 0, keep the substring from i to j when it is shorter than the answer, and leave the inner loop.
  4. Return the answer.
A
D
B
E
C
A
012345
ij
A→0
B→1
C→1
take A, missing 2
1 / 21

We leave the inner loop as soon as the substring contains every character of t, without checking the longer substrings, because every one of them is longer than the one we have just found.

Code

Code
Python
def minWindow(s: str, t: str) -> str:
result = ''
for i in range(len(s)):
characters = counts(t)
missing = len(t)
for j in range(i, len(s)):
c = s[j]
if c in characters and characters[c] > 0:
characters[c] -= 1
missing -= 1
if missing == 0:
if not result or j - i + 1 < len(result):
result = s[i:j + 1]
break
return result
def counts(text: str) -> dict[str, int]:
result = {}
for c in text:
result[c] = result.get(c, 0) + 1
return result
/**
* @param {string} s
* @param {string} t
* @returns {string}
*/
var minWindow = function (s, t) {
let result = ''
for (let i = 0; i < s.length; i++) {
const characters = counts(t)
let missing = t.length
for (let j = i; j < s.length; j++) {
const c = s[j]
if (characters.has(c) && characters.get(c) > 0) {
characters.set(c, characters.get(c) - 1)
missing--
}
if (missing === 0) {
if (!result || j - i + 1 < result.length) result = s.slice(i, j + 1)
break
}
}
}
return result
}
var counts = function (text) {
const result = new Map()
for (const c of text) result.set(c, (result.get(c) ?? 0) + 1)
return result
}
import java.util.HashMap;
import java.util.Map;
class Solution {
public String minWindow(String s, String t) {
String result = "";
for (int i = 0; i < s.length(); i++) {
Map<Character, Integer> characters = counts(t);
int missing = t.length();
for (int j = i; j < s.length(); j++) {
char c = s.charAt(j);
if (characters.containsKey(c) && characters.get(c) > 0) {
characters.merge(c, -1, Integer::sum);
missing--;
}
if (missing == 0) {
if (result.isEmpty() || j - i + 1 < result.length()) result = s.substring(i, j + 1);
break;
}
}
}
return result;
}
private Map<Character, Integer> counts(String text) {
Map<Character, Integer> result = new HashMap<>();
for (char c : text.toCharArray()) result.merge(c, 1, Integer::sum);
return result;
}
}

2. Sliding Window

O(n + m) time | O(m) space, for t of length m

Intuition

We can keep one substring as a window between the left and right indexes, and extend it by moving right one character forward.

When the window contains every character of t, we move left forward until it is missing one of them again.

When we move right forward, left never goes back towards the start, because we know that every window that starts before it is longer than the one we have already found.

Algorithm

  1. Create a hash map with how many times each character appears in t, and a missing integer variable with the length of t.
  2. Create a left index variable with initial value 0 and an empty string for the answer.
  3. Iterate through the loop from the first character to the last character with right index.
    • When the hash map has a key for the character at right, subtract one from its value, and decrease missing by one unless that value went below 0.
    • While missing is 0, keep the substring from left to right when it is shorter than the answer, then when the hash map has a key for the character at left, add one back to its value and increase missing by one when that value goes above 0, and move left one step to the right.
  4. Return the answer.
A
D
B
E
C
A
012345
leftright
A→0
B→1
C→1
take A, missing 2
1 / 10

Code

Code
Python
def minWindow(s: str, t: str) -> str:
characters = counts(t)
missing = len(t)
result = ''
left = 0
for right in range(len(s)):
c = s[right]
if c in characters:
characters[c] -= 1
if characters[c] >= 0:
missing -= 1
while missing == 0:
if not result or right - left + 1 < len(result):
result = s[left:right + 1]
released = s[left]
if released in characters:
characters[released] += 1
if characters[released] > 0:
missing += 1
left += 1
return result
def counts(text: str) -> dict[str, int]:
result = {}
for c in text:
result[c] = result.get(c, 0) + 1
return result
/**
* @param {string} s
* @param {string} t
* @returns {string}
*/
var minWindow = function (s, t) {
const characters = counts(t)
let missing = t.length
let result = ''
let left = 0
for (let right = 0; right < s.length; right++) {
const c = s[right]
if (characters.has(c)) {
characters.set(c, characters.get(c) - 1)
if (characters.get(c) >= 0) missing--
}
while (missing === 0) {
if (!result || right - left + 1 < result.length) result = s.slice(left, right + 1)
const released = s[left]
if (characters.has(released)) {
characters.set(released, characters.get(released) + 1)
if (characters.get(released) > 0) missing++
}
left++
}
}
return result
}
var counts = function (text) {
const result = new Map()
for (const c of text) result.set(c, (result.get(c) ?? 0) + 1)
return result
}
import java.util.HashMap;
import java.util.Map;
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> characters = counts(t);
int missing = t.length();
String result = "";
int left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (characters.containsKey(c)) {
characters.merge(c, -1, Integer::sum);
if (characters.get(c) >= 0) missing--;
}
while (missing == 0) {
if (result.isEmpty() || right - left + 1 < result.length()) result = s.substring(left, right + 1);
char released = s.charAt(left);
if (characters.containsKey(released)) {
characters.merge(released, 1, Integer::sum);
if (characters.get(released) > 0) missing++;
}
left++;
}
}
return result;
}
private Map<Character, Integer> counts(String text) {
Map<Character, Integer> result = new HashMap<>();
for (char c : text.toCharArray()) result.merge(c, 1, Integer::sum);
return result;
}
}
Was the explanation clear?
def minWindow(s: str, t: str) -> str:
pass
 

Press Visualise to step through your code.