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.