Skip to content

Permutation in String

Check whether s2 contains a rearrangement of s1, sliding a fixed-size window of letter counts.

MediumSliding Window
Solve on LeetCode

The problem

You get two strings s1 and s2 made of lowercase English letters. Return true if some permutation of s1, meaning the same letters in any order, appears as a contiguous substring of s2, and false otherwise.

Input s1 = "ate", s2 = "greatest"

Output true

The block "eat" inside "greatest" uses the same letters as "ate".

Input s1 = "pin", s2 = "spain"

Output false

Every letter of "pin" is in "spain", but never side by side in one block of three.

How to spot the pattern

  • A permutation is just a set of letter counts, so the order inside the block doesn't matter.
  • The block you are looking for always has the length of s1, which means a window of fixed size.

The idea

Any permutation of s1 has exactly the same letter counts as s1. So slide a window of length len(s1) across s2, and keep the window's letter counts up to date as one letter enters on the right and one leaves on the left. If the window's counts ever equal the counts of s1, that block is a permutation.

Brute force: Sort every block of s2 that has the length of s1 and compare it with sorted s1, which takes O(n * m log m) time.

Step by step

  1. 1If s1 is longer than s2, return false.
  2. 2Count the letters of s1, and of the first len(s1) letters of s2, in two arrays of 26.
  3. 3If the two arrays are equal, return true.
  4. 4Slide the window one step at a time: add the letter that enters, remove the letter that leaves, and compare the arrays again.
  5. 5If no window matched, return false.

See the pattern move

The sliding window pattern on a small example. Step through it, or press play.

Code

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        m = len(s1)
        if m > len(s2):
            return False
        need = [0] * 26  # letter counts of s1
        window = [0] * 26  # letter counts of the current block of s2
        for i in range(m):
            need[ord(s1[i]) - ord("a")] += 1
            window[ord(s2[i]) - ord("a")] += 1
        if window == need:
            return True
        for right in range(m, len(s2)):
            window[ord(s2[right]) - ord("a")] += 1  # letter entering
            window[ord(s2[right - m]) - ord("a")] -= 1  # letter leaving
            if window == need:
                return True
        return False

Complexity

Time

O(n)

Space

O(1)

Each slide updates two counts and compares 26 pairs, so the total is about 26 n steps for a string s2 of length n; the arrays always have 26 slots.

Watch out for

  • Rebuilding or sorting each window from scratch, which costs O(m) or more per step instead of O(1) updates.
  • Forgetting the case where s1 is longer than s2, so the first window runs past the end.
  • Comparing only after the first slide, which misses a match in the very first window.

Follow-up questions

Can you avoid comparing all 26 counts at every step?

Keep a matches counter of how many letters have equal counts in both arrays. A slide changes at most two letters, so you update matches in O(1) and check matches == 26.

What if you need every start index of a permutation of s1 inside s2?

Use the same window, but record the start of every matching window instead of returning at the first one. That is Find All Anagrams in a String.

In Hinglish

s1 ki length ki window s2 par chalao; ek letter andar aata hai, ek bahar jaata hai. Window ki ginti s1 ki ginti se match ho jaaye toh mil gaya.

Related problems