Faaez Razeen

Minimum Window Substring

  • 2 min read
  • String
  • LC-Hard
  • Sliding Window

3 years ago

Solution

TimeSpaceExplanation
O(n)O(1)The charset is limited to 26 characters- and there's only one entry per character in the string for both the counters, so the space complexity is constant
def minWindow(self, s: str, t: str) -> str: if len(t) > len(s): return '' s_count = defaultdict(lambda: 0) t_count = Counter(t) l = have = 0 needed = len(t_count.keys()) ans = None for r in range(len(s)): ch = s[r] s_count[ch] += 1 if ch in t_count and s_count[ch] == t_count[ch]: have += 1 while have == needed: if ans is None or r - l + 1 < (ans[1] - ans[0] + 1): ans = [l, r] ch = s[l] s_count[ch] -= 1 if ch in t_count and s_count[ch] + 1 == t_count[ch]: have -= 1 l += 1 if ans is None: return '' return s[ans[0]:ans[1]+1]