Advertisement
Iam_Sandeep

76. Minimum Window Substring

Jun 18th, 2022
825
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. '''
  2. watch neetcode video beautiful explanation
  3. Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
  4.  
  5. The testcases will be generated such that the answer is unique.
  6.  
  7. A substring is a contiguous sequence of characters within the string.
  8. '''
  9. class Solution:
  10.     def minWindow(self, s: str, t: str) -> str:
  11.         countT={}
  12.         window={}
  13.         l=0
  14.         res=[-1,-1]
  15.         reslen=float('inf')
  16.         have,need=0,0
  17.        
  18.         for i in t:
  19.             countT[i]=countT.get(i,0)+1
  20.        
  21.         need=len(countT)
  22.        
  23.         for r in range(len(s)):
  24.             c=s[r]
  25.             window[c]=window.get(c,0)+1
  26.             if c in countT and countT[c]==window[c]:
  27.                 have+=1
  28.             while have==need:
  29.                
  30.                 if r-l+1<reslen:
  31.                     res=[l,r]
  32.                     reslen=r-l+1
  33.        
  34.                 window[s[l]]-=1
  35.                 if s[l] in countT and window[s[l]]<countT[s[l]]:
  36.                     have=have-1
  37.                 l=l+1
  38.         l,r=res
  39.         return s[l:r+1] if reslen!=float('inf') else ""
  40.            
  41.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement