Permutation in String (LeetCode 567): Solution and Explanation
Given two lowercase strings s1 and s2, decide whether s2 contains some rearrangement of s1 as a contiguous substring. In other words, check whether any window of s2 with the same length as s1 uses exactly the same letters with the same counts.
Watch it run step by step
Try your own input and write the code →Intuition
Generating every permutation of s1 and searching for each one is hopeless, since a string of length 10 already has millions of orderings. The useful observation is that order does not matter at all. Two strings are permutations of each other exactly when their letter counts match, so the question becomes whether any window of length len(s1) in s2 has the same 26 counts as s1.
You could slide that window across s2 and compare both count arrays at every position. That is O(26 × n), which is already linear and perfectly acceptable. But each slide only changes two counts: one letter enters on the right and one leaves on the left. Comparing all 26 entries every time throws that fact away.
So track a single number, matches, the count of letters whose frequencies currently agree between the two arrays. When a letter's count changes, only that letter's match status can flip. If it just became equal, matches goes up by one; if it was equal and just moved away by one, matches goes down by one. When matches reaches 26, every letter agrees and the current window is a permutation of s1.
Approach: Fixed sliding window with a matches counter
- If
s1is longer thans2, return False because no window can fit. - Build 26-entry count arrays for
s1and for the firstlen(s1)characters ofs2. - Set
matchesto the number of letters whose counts are equal in both arrays. - Slide the window one position at a time. Before each slide, return True if
matches == 26. - Add the incoming letter
s2[i + len(s1)]: if its count now equals thes1count, incrementmatches; if it just went one above, decrementmatches. - Remove the outgoing letter
s2[i]: if its count now equals thes1count, incrementmatches; if it just dropped one below, decrementmatches. After the loop, return whether the final window hasmatches == 26.
Step-by-step example
s1 = "ab", s2 = "eidbaooo"
- The first window is "ei". The letters a, b, e and i disagree, so
matchesstarts at 22. - Slide to "id": adding d pushes it one above its target, so
matchesdrops to 21, and removing e restores e, bringingmatchesback to 22. - Slide to "db": adding b makes b match, so
matchesis 23, and removing i makes i match, somatchesis 24. - Slide to "ba": adding a makes a match, so
matchesis 25, and removing d makes d match, somatchesis 26. - At the top of the next iteration
matchesequals 26, so the function returns True because "ba" is a permutation of "ab".
Code: Python, Java, C++
1class Solution:
2 def checkInclusion(self, s1: str, s2: str) -> bool:
3 if len(s1) > len(s2):
4 return False
5 s1_count = [0] * 26
6 s2_count = [0] * 26
7 for i in range(len(s1)):
8 s1_count[ord(s1[i]) - ord('a')] += 1
9 s2_count[ord(s2[i]) - ord('a')] += 1
10 matches = sum(1 for i in range(26) if s1_count[i] == s2_count[i])
11 for i in range(len(s2) - len(s1)):
12 if matches == 26:
13 return True
14 left = ord(s2[i]) - ord('a')
15 right = ord(s2[i + len(s1)]) - ord('a')
16 s2_count[right] += 1
17 if s2_count[right] == s1_count[right]:
18 matches += 1
19 elif s2_count[right] == s1_count[right] + 1:
20 matches -= 1
21 s2_count[left] -= 1
22 if s2_count[left] == s1_count[left]:
23 matches += 1
24 elif s2_count[left] == s1_count[left] - 1:
25 matches -= 1
26 return matches == 261class Solution {
2 public boolean checkInclusion(String s1, String s2) {
3 if (s1.length() > s2.length()) return false;
4 int[] s1Count = new int[26];
5 int[] s2Count = new int[26];
6 for (int i = 0; i < s1.length(); i++) {
7 s1Count[s1.charAt(i) - 'a']++;
8 s2Count[s2.charAt(i) - 'a']++;
9 }
10 int matches = 0;
11 for (int i = 0; i < 26; i++) {
12 if (s1Count[i] == s2Count[i]) matches++;
13 }
14 for (int i = 0; i < s2.length() - s1.length(); i++) {
15 if (matches == 26) return true;
16 int left = s2.charAt(i) - 'a';
17 int right = s2.charAt(i + s1.length()) - 'a';
18 s2Count[right]++;
19 if (s2Count[right] == s1Count[right]) matches++;
20 else if (s2Count[right] == s1Count[right] + 1) matches--;
21 s2Count[left]--;
22 if (s2Count[left] == s1Count[left]) matches++;
23 else if (s2Count[left] == s1Count[left] - 1) matches--;
24 }
25 return matches == 26;
26 }
27}1class Solution {
2public:
3 bool checkInclusion(string s1, string s2) {
4 if (s1.length() > s2.length()) return false;
5 vector<int> s1Count(26, 0), s2Count(26, 0);
6 for (int i = 0; i < s1.length(); i++) {
7 s1Count[s1[i] - 'a']++;
8 s2Count[s2[i] - 'a']++;
9 }
10 int matches = 0;
11 for (int i = 0; i < 26; i++) {
12 if (s1Count[i] == s2Count[i]) matches++;
13 }
14 for (int i = 0; i < s2.length() - s1.length(); i++) {
15 if (matches == 26) return true;
16 int left = s2[i] - 'a';
17 int right = s2[i + s1.length()] - 'a';
18 s2Count[right]++;
19 if (s2Count[right] == s1Count[right]) matches++;
20 else if (s2Count[right] == s1Count[right] + 1) matches--;
21 s2Count[left]--;
22 if (s2Count[left] == s1Count[left]) matches++;
23 else if (s2Count[left] == s1Count[left] - 1) matches--;
24 }
25 return matches == 26;
26 }
27};Time and space complexity
O(n)
Here n is the length of s2. Building the initial counts and computing matches takes O(len(s1) + 26), and each slide does constant work.
O(1)
Both count arrays have a fixed size of 26, independent of the input lengths.
Other approaches
Compare full count arrays each step (time O(26 × n), space O(1))
Slide the window and compare the two 26-entry arrays directly at every position. It is simpler and still linear, just with a constant factor of 26 per step.
Sort each window (time O(n × m log m), space O(m))
Sort s1 once and sort every window of s2 of the same length, comparing the results. It is easy to write but much slower on long inputs.
Common mistakes
- Forgetting the final check after the loop. The loop only checks before sliding, so the last window must be tested separately with
matches == 26. - Changing
matcheswhenever a count changes rather than only when that letter's match status flips. A count moving from two above to one above should not affectmatches. - Mapping letters with
ord(c)instead oford(c) - ord('a'), which indexes far outside the 26-entry arrays. - Skipping the length check, which leads to an index error when
s1is longer thans2.
Frequently asked questions
How do you check if a string contains a permutation of another string?
Slide a window of the shorter string's length across the longer string and compare letter counts. Any window whose counts match is a permutation, and keeping a matches counter makes each slide O(1).
What is the time complexity of Permutation in String?
It is O(n) for the length of s2, plus a small constant for the 26-letter alphabet. The space is O(1).
How is this related to Find All Anagrams in a String?
It is the same sliding window. Here you return True at the first match, while the anagrams problem collects every starting index where the counts match.