Back to Problem
Official
722 views
Editorial: Permutation in String
by admin ·
21
1 Intuition
Two strings are permutations of each other iff their letter counts match.
2 Approach
Slide a fixed-size window of length |s1| over s2 and compare letter counts as it moves.
3 Complexity Analysis
Time O(26 · |s2|), Space O(1).
4 Solution Code
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
from collections import Counter
n = len(s1)
need, window = Counter(s1), Counter(s2[:n])
if window == need:
return True
for i in range(n, len(s2)):
window[s2[i]] += 1
window[s2[i - n]] -= 1
if window == need:
return True
return False
5 Code Walkthrough
The reference solution below implements the approach step by step.