#76
Minimum Window Substring
HardHash TableStringSliding WindowHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses the sliding window technique with two pointers to efficiently find the minimum window. This reduces the time complexity significantly by avoiding unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Create a frequency map of characters in 't'.
- 2Step 2: Use two pointers to create a window in 's'. Expand the right pointer to include characters until the window contains all characters from 't'.
- 3Step 3: Once all characters are included, move the left pointer to minimize the window while still containing all characters from 't'.
- 4Step 4: Keep track of the minimum length window found.
solution.py31 lines
1from collections import Counter, defaultdict
2
3def min_window(s, t):
4 if not t or not s:
5 return ""
6 dict_t = Counter(t)
7 required = len(dict_t)
8 l, r = 0, 0
9 formed = 0
10 window_counts = defaultdict(int)
11 min_len = float('inf')
12 min_window = (0, 0)
13
14 while r < len(s):
15 character = s[r]
16 window_counts[character] += 1
17 if character in dict_t and window_counts[character] == dict_t[character]:
18 formed += 1
19
20 while l <= r and formed == required:
21 character = s[l]
22 if r - l + 1 < min_len:
23 min_len = r - l + 1
24 min_window = (l, r)
25 window_counts[character] -= 1
26 if character in dict_t and window_counts[character] < dict_t[character]:
27 formed -= 1
28 l += 1
29 r += 1
30
31 return "" if min_len == float('inf') else s[min_window[0]:min_window[1] + 1]ℹ
Complexity note: The time complexity is O(n) because we traverse the string 's' at most twice (once with the right pointer and once with the left pointer). The space complexity is O(n) due to the storage of character counts in the frequency maps.
- 1Using a sliding window allows us to dynamically adjust our search space, making it efficient.
- 2Character frequency maps help in quickly checking if a window contains all required characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.