Minimum Window Substring
LeetCode 76 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Expand to valid, shrink to minimal; 'formed' counts satisfied characters.
நான் Minimum Window Substring (LeetCode 76) ஐ இப்படித் தீர்த்தேன் — Sliding Window பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Expand the right edge until the window contains every required character in the right quantity; then shrink from the left as far as possible while it stays valid, recording the smallest window. Repeat for every right edge.
Approach
- 1
Count requirements from t; required = number of distinct characters.
- 2
Add s[r] to the window; when its count reaches the need, formed++.
- 3
While formed == required: record the window, remove s[l], update formed, l++.
- 4
Return the best window.
நான் எப்படித் தீர்த்தேன்
Sliding window with countsPythonO(n) time
class Solution:
def minWindow(self, s: str, t: str) -> str:
req_freq_map = Counter(t)
required = len(req_freq_map)
window_map_freq = defaultdict(int)
l=0
r=0
s_index=None
r_index=None
formed=0
min_length = float("inf")
while r<len(s):
char=s[r]
window_map_freq[char]+=1
if char in req_freq_map and window_map_freq[char]==req_freq_map[char]:
formed+=1
#shrink
while l<=r and formed==required:
left_most_char = s[l]
window_map_freq[left_most_char]-=1
if r-l+1<min_length:
min_length = r-l+1
s_index=l
r_index=r
if left_most_char in req_freq_map and window_map_freq[left_most_char]<req_freq_map[left_most_char]:
formed-=1
l+=1
r+=1
return s[s_index:r_index+1] if s_index!=None and r_index!=None else ""
Minimum Window Substring — அடிக்கடி கேட்கப்படும் கேள்விகள்
Minimum Window Substring பின்னாலுள்ள intuition என்ன?
Expand the right edge until the window contains every required character in the right quantity; then shrink from the left as far as possible while it stays valid, recording the smallest window. Repeat for every right edge.
Minimum Window Substring (LeetCode 76) ஐ எப்படித் தீர்ப்பது?
1. Count requirements from t; required = number of distinct characters. 2. Add s[r] to the window; when its count reaches the need, formed++. 3. While formed == required: record the window, remove s[l], update formed, l++. 4. Return the best window.
Minimum Window Substring இன் time மற்றும் space complexity என்ன?
Time: O(|s| + |t|). Space: O(Σ). (Accepted approach: Sliding window with counts.)
Minimum Window Substring இல் பொதுவான தவறுகள் என்ன?
formed should change only when a count crosses the requirement exactly. Return '' when no window is ever valid.