- Link: 567. Permutation in String - Medium
- Track: NeetCode150
Question
Restate the problem
- Given two strings
s1ands2 - Return
Trueif some permutation ofs1appears as a substring ins2; otherwise returnFalse.
In other words, check whether s2 contains a substring of length len(s1) whose character frequency is exactly the same as s1.
Edge Case
len(s1) > len(s2)→ impossible, returnFalses1ands2contain only lowercase English letters- We need an exact frequency match, not just the same set of characters
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Sliding window |
Method 1 - Sliding window
The key idea is to use a frequency array of size 26 to record the character counts.
Approach
- Use a fixed-size sliding window of length
len(s1)overs2. - First, count the frequency of each character in
s1using an arrayneedof size 26.need[i]means how many more of that character are still needed for the current window to matchs1.
- As the right pointer expands the window:
- subtract the new character from
need
- subtract the new character from
- If the window becomes longer than
len(s1):- remove the left character from the window
- add it back to
need
- If at any point
need == [0] * 26, then the current window has exactly the same character counts ass1, so returnTrue.
Complexity
- Time Complexity:
- Space Complexity:
- Fixed size 26
Code
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
need = [0] * 26
zero = [0] * 26
for char in s1:
idx = ord(char) - ord('a')
need[idx] += 1
left = right = 0
while right < len(s2):
idx = ord(s2[right]) - ord('a') # e - a
need[idx] -= 1
if right - left + 1 > len(s1):
idx = ord(s2[left]) - ord('a')
need[idx] += 1
left += 1
if need == zero:
return True
right += 1
return FalseMistake
- fixed-size sliding window