imashutosh51

Smallest distinct window

Jul 31st, 2022 (edited)
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. '''
  2. TC O(N)
  3. Logic:we will have a window and a map,map will store count of all chars in window.
  4. we will keep count of distinct character of window using map and when it equals to
  5. distinct characters in map,then we have a substring with all distinct character
  6. .now there is possibility that some characters got repeated
  7. so we will shrink our window from left dise till our window have every distinct character
  8. then we will update our ans.now we will reduce one distinct character from our window
  9. and search for other possibility and do same for new window.
  10. '''
  11.  
  12. import math
  13.  
  14. class Solution:
  15.     def findSubString(self, s):
  16.         need_dict={}
  17.         for i in s:
  18.             if need_dict.get(i,0)==0:
  19.                 need_dict[i]=1
  20.  
  21.         need=len(need_dict)
  22.  
  23.         cur_window={}
  24.         start=0
  25.         ans=math.inf
  26.  
  27.         for i in range(len(s)):
  28.             if cur_window.get(s[i],0) < need_dict.get(s[i],0):
  29.                 cur_window[s[i]]=cur_window.get(s[i],0)+1
  30.                 need-=1
  31.             else:
  32.                 cur_window[s[i]]=cur_window.get(s[i],0)+1
  33.  
  34.             while need==0:
  35.                 # CHANGED: Update answer before shrinking the window
  36.                 ans=min(ans,i-start+1)
  37.  
  38.                 # CHANGED: Decrease frequency of the leftmost character
  39.                 cur_window[s[start]]-=1
  40.  
  41.                 # CHANGED: Check if removing the character makes window invalid
  42.                 if cur_window[s[start]] < need_dict.get(s[start],0):
  43.                     need+=1
  44.  
  45.                 start+=1
  46.  
  47.         # CHANGED: Return 0 if no valid window exists
  48.         return ans if ans!=math.inf else 0
Advertisement
Add Comment
Please, Sign In to add comment