|
| 1 | +# 76. Minimum Window Substring |
| 2 | + |
| 3 | +## Sliding Window with Dictionary Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of characters in S |
| 7 | + |
| 8 | +Lets focus on how to figure out if a sub-string has all characters of T. |
| 9 | +You can do this with a dictionary counter, keeping occurances of each character of T. |
| 10 | +To avoid checking if each character in the dictionary is less than or equal to zero occurances, we can keep a separate variable as the remmaining characters needed to be found. |
| 11 | + |
| 12 | +Next is the idea of a sliding window, if we iterate from left to right, we can find all the sub-strings containing T using the above soluiton. |
| 13 | +Once that sub-string is found, then its the matter of decrementing the left most character of the sub-string until we need to find another character. |
| 14 | +With that, we have to decrement the dictionary and the number of remaining characters accordingly. |
| 15 | + |
| 16 | +``` |
| 17 | +from collections import Counter |
| 18 | +
|
| 19 | +class Solution: |
| 20 | + def minWindow(self, s: str, t: str) -> str: |
| 21 | + char_counter = Counter(t) |
| 22 | + left_idx, n_chars_needed = 0, len(t) |
| 23 | + result = (-1, -1) # left and right result indexes |
| 24 | + |
| 25 | + for right_idx, ch in enumerate(s): |
| 26 | + if ch in char_counter: |
| 27 | + char_counter[ch] -= 1 |
| 28 | + if char_counter[ch] >= 0: |
| 29 | + n_chars_needed -= 1 |
| 30 | + |
| 31 | + while n_chars_needed == 0: |
| 32 | + if result[0] == -1 or result[1]-result[0] > right_idx-left_idx: |
| 33 | + result = (left_idx, right_idx) |
| 34 | + left_ch = s[left_idx] |
| 35 | + if left_ch in char_counter: |
| 36 | + char_counter[left_ch] += 1 |
| 37 | + if char_counter[left_ch] == 1: |
| 38 | + n_chars_needed += 1 |
| 39 | + left_idx += 1 |
| 40 | + |
| 41 | + return s[result[0]:result[1]+1] if result[0] != -1 else '' |
| 42 | +``` |
0 commit comments