Permutation in String (LeetCode 567): Solution and Explanation

Medium
Hash Table
Two Pointers
String
Sliding Window

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. If s1 is longer than s2, return False because no window can fit.
  2. Build 26-entry count arrays for s1 and for the first len(s1) characters of s2.
  3. Set matches to the number of letters whose counts are equal in both arrays.
  4. Slide the window one position at a time. Before each slide, return True if matches == 26.
  5. Add the incoming letter s2[i + len(s1)]: if its count now equals the s1 count, increment matches; if it just went one above, decrement matches.
  6. Remove the outgoing letter s2[i]: if its count now equals the s1 count, increment matches; if it just dropped one below, decrement matches. After the loop, return whether the final window has matches == 26.

Step-by-step example

s1 = "ab", s2 = "eidbaooo"
  1. The first window is "ei". The letters a, b, e and i disagree, so matches starts at 22.
  2. Slide to "id": adding d pushes it one above its target, so matches drops to 21, and removing e restores e, bringing matches back to 22.
  3. Slide to "db": adding b makes b match, so matches is 23, and removing i makes i match, so matches is 24.
  4. Slide to "ba": adding a makes a match, so matches is 25, and removing d makes d match, so matches is 26.
  5. At the top of the next iteration matches equals 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 == 26

Time and space complexity

Time

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.

Space

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 matches whenever a count changes rather than only when that letter's match status flips. A count moving from two above to one above should not affect matches.
  • Mapping letters with ord(c) instead of ord(c) - ord('a'), which indexes far outside the 26-entry arrays.
  • Skipping the length check, which leads to an index error when s1 is longer than s2.

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.