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
- Create an empty string for the answer.
- Iterate through the outer loop from the first character to the last character with
iindex. - For each outer loop iteration, create a hash map with how many times each character appears in
t, amissinginteger variable with the length oft, and iterate through the inner loop from the character atito the last character withjindex.- When the hash map has a key for the character at
jwith a value above0, subtract one from that value and decreasemissingby one. - When
missingis0, keep the substring fromitojwhen it is shorter than the answer, and leave the inner loop.
- When the hash map has a key for the character at
- Return the answer.
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
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
- Create a hash map with how many times each character appears in
t, and amissinginteger variable with the length oft. - Create a
leftindex variable with initial value0and an empty string for the answer. - Iterate through the loop from the first character to the last character with
rightindex.- When the hash map has a key for the character at
right, subtract one from its value, and decreasemissingby one unless that value went below0. - While
missingis0, keep the substring fromlefttorightwhen it is shorter than the answer, then when the hash map has a key for the character atleft, add one back to its value and increasemissingby one when that value goes above0, and moveleftone step to the right.
- When the hash map has a key for the character at
- Return the answer.
Code
def minWindow(s: str, t: str) -> str: pass Press Visualise to step through your code.