imashutosh51

Minimum Window substring

Oct 29th, 2022 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. '''
  2. count is a map which will keep the each character count in string t because duplicate character can be in t.
  3. need is actually how many minimum characters must be present in window.
  4. winodw map will keep the store the count of characters in current window.
  5. if we get any character whose count in window is less than count of character in t then we got one needed
  6. character so decrease need and update the window map.
  7. if need==0 means we have all the needed characters in window,so we will update the answer.Now decrease the
  8. charcters from left and if you loose one needed one character then update the answer with including that lost
  9. character and now traverse ahead but we have need of one character.
  10. '''
  11. import math
  12.  
  13. class Solution:
  14.     def minWindow(self, s: str, t: str) -> str:
  15.         target_count = {}
  16.         for char in t:
  17.             target_count[char] = target_count.get(char, 0) + 1
  18.  
  19.         need = len(t)
  20.         left = 0
  21.         window_count = {}
  22.         min_length = math.inf
  23.         start = 0
  24.  
  25.         for right in range(len(s)):
  26.             char = s[right]
  27.  
  28.             if target_count.get(char, 0) > window_count.get(char, 0):
  29.                 window_count[char] = window_count.get(char, 0) + 1
  30.                 need -= 1
  31.             else:
  32.                 window_count[char] = window_count.get(char, 0) + 1
  33.  
  34.             while need == 0:
  35.                 # Update the minimum valid window
  36.                 if right - left + 1 < min_length:
  37.                     min_length = right - left + 1
  38.                     start = left
  39.  
  40.                 # Remove the leftmost character
  41.                 window_count[s[left]] -= 1
  42.  
  43.                 # Check if removing this character makes the window invalid
  44.                 if window_count[s[left]] < target_count.get(s[left], 0):
  45.                     need += 1
  46.  
  47.                 left += 1
  48.  
  49.         return s[start:start + min_length] if min_length != math.inf else ""
  50.  
Advertisement
Add Comment
Please, Sign In to add comment