Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- count is a map which will keep the each character count in string t because duplicate character can be in t.
- need is actually how many minimum characters must be present in window.
- winodw map will keep the store the count of characters in current window.
- if we get any character whose count in window is less than count of character in t then we got one needed
- character so decrease need and update the window map.
- if need==0 means we have all the needed characters in window,so we will update the answer.Now decrease the
- charcters from left and if you loose one needed one character then update the answer with including that lost
- character and now traverse ahead but we have need of one character.
- '''
- import math
- class Solution:
- def minWindow(self, s: str, t: str) -> str:
- target_count = {}
- for char in t:
- target_count[char] = target_count.get(char, 0) + 1
- need = len(t)
- left = 0
- window_count = {}
- min_length = math.inf
- start = 0
- for right in range(len(s)):
- char = s[right]
- if target_count.get(char, 0) > window_count.get(char, 0):
- window_count[char] = window_count.get(char, 0) + 1
- need -= 1
- else:
- window_count[char] = window_count.get(char, 0) + 1
- while need == 0:
- # Update the minimum valid window
- if right - left + 1 < min_length:
- min_length = right - left + 1
- start = left
- # Remove the leftmost character
- window_count[s[left]] -= 1
- # Check if removing this character makes the window invalid
- if window_count[s[left]] < target_count.get(s[left], 0):
- need += 1
- left += 1
- return s[start:start + min_length] if min_length != math.inf else ""
Advertisement
Add Comment
Please, Sign In to add comment