Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- TC O(N)
- Logic:we will have a window and a map,map will store count of all chars in window.
- we will keep count of distinct character of window using map and when it equals to
- distinct characters in map,then we have a substring with all distinct character
- .now there is possibility that some characters got repeated
- so we will shrink our window from left dise till our window have every distinct character
- then we will update our ans.now we will reduce one distinct character from our window
- and search for other possibility and do same for new window.
- '''
- import math
- class Solution:
- def findSubString(self, s):
- need_dict={}
- for i in s:
- if need_dict.get(i,0)==0:
- need_dict[i]=1
- need=len(need_dict)
- cur_window={}
- start=0
- ans=math.inf
- for i in range(len(s)):
- if cur_window.get(s[i],0) < need_dict.get(s[i],0):
- cur_window[s[i]]=cur_window.get(s[i],0)+1
- need-=1
- else:
- cur_window[s[i]]=cur_window.get(s[i],0)+1
- while need==0:
- # CHANGED: Update answer before shrinking the window
- ans=min(ans,i-start+1)
- # CHANGED: Decrease frequency of the leftmost character
- cur_window[s[start]]-=1
- # CHANGED: Check if removing the character makes window invalid
- if cur_window[s[start]] < need_dict.get(s[start],0):
- need+=1
- start+=1
- # CHANGED: Return 0 if no valid window exists
- return ans if ans!=math.inf else 0
Advertisement
Add Comment
Please, Sign In to add comment