Permutation in String
LeetCode 567 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Fixed-size window with matching counts.
నేను Permutation in String (LeetCode 567) ను ఇలా పరిష్కరించాను — Fixed Window ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
A permutation of s1 is just a window of the same length in s2 with identical letter counts. Slide a window of size len(s1) over s2 and compare counts.
Approach
- 1
Count s1.
- 2
Add s2[r]; drop s2[l] when the window exceeds len(s1).
- 3
Return True as soon as counts are equal.
నేను ఎలా పరిష్కరించాను
Sliding window countsPythonO(n) time
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
mpp = defaultdict(int)
for char in s1:
mpp[char]+=1
l=0
r=0
cur_freq_mpp=defaultdict(int)
while r<len(s2):
cur = s2[r]
cur_freq_mpp[cur]+=1
if r-l+1 > len(s1):
#shrink
cur_freq_mpp[s2[l]]-=1
if cur_freq_mpp[s2[l]]==0:
del cur_freq_mpp[s2[l]]
l+=1
if mpp==cur_freq_mpp:
return True
r+=1
return False
Permutation in String — తరచూ అడిగే ప్రశ్నలు
Permutation in String వెనుక ఉన్న intuition ఏమిటి?
A permutation of s1 is just a window of the same length in s2 with identical letter counts. Slide a window of size len(s1) over s2 and compare counts.
Permutation in String (LeetCode 567) ను ఎలా పరిష్కరించాలి?
1. Count s1. 2. Add s2[r]; drop s2[l] when the window exceeds len(s1). 3. Return True as soon as counts are equal.
Permutation in String యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(Σ). (Accepted approach: Sliding window counts.)
Permutation in String లో సాధారణ పొరపాట్లు ఏమిటి?
Delete zero counts so dict comparison is accurate.