Permutation in String

Medium

Topics
StringSliding WindowHash Table

Given two strings s1 and s2, return true if s2 contains a permutation of s1 as a contiguous substring. (Here the first line is s1, the second is s2.)

Example 1

patternab
searcheidbaooo
a permutation of ab
A shaded stretch is a window of eidbaooo holding exactly the letters of ab in some order, starting at index 3 — so the answer is true. Re-sorting each window would cost n·k log k; instead the window’s letter counts take one add and one remove per step, making the scan linear.
Top row is the pattern; bottom row is the string being searched.
Input:  s1 = "ab", s2 = "eidbaooo"
Output: true

Example 2

patternab
searcheidbaooo
a permutation of ab
Input:  s1 = "ab", s2 = "eidboaoo"
Output: false

Constraints

  • 1 <= s1.length, s2.length <= 10^4
  • s1 and s2 consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A permutation of s1 is any window of s2 with the same letter counts as s1. Slide a fixed-size window (length |s1|) over s2 and compare frequency vectors.

Approach

  1. Build the 26-length count of s1 and of the first window of s2.
  2. Slide the window one char at a time, updating counts in O(1).
  3. Return true whenever the counts match.

Dry Run

s = "ab", t = "eidbaooo"
need = {a:1, b:1}. The window is a fixed width of len(s) = 2 that slides.
  i=0 add e                     window {e:1}
  i=1 add i                     window {e:1, i:1}
  i=2 add d, evict e            window {d:1, i:1}
  i=3 add b, evict i            window {b:1, d:1}
  i=4 add a, evict d            window {a:1, b:1}   == need  ->  true
answer true
The eviction at `i >= len(s)` is what makes this a window rather than a growing
prefix. Remove it and the counts only ever increase, so once the window is wider
than s they can never equal `need` again -- this input then returns false, missing
the permutation at index 3.
Comparing two 26-element lists looks expensive inside a loop and is not: 26 is a
constant, so the whole scan is O(26n) = O(n). The alternative, sorting each
window and comparing strings, would be O(n k log k) -- asymptotically worse for
exactly the reason that looks like a micro-optimisation here.
Order never matters to the test. A permutation is a multiset, so counts are
precisely the right representation and nothing about position is tracked.

Complexity

  • Time — O(n): each character enters and leaves the window once; comparison is O(26).
  • Space — O(1): two fixed 26-length arrays.

Common Pitfalls

  • The window has to shrink. Without the removal at i - len(s) the counts only ever grow, so after the window is full they can never match again and a permutation later in the string is missed.
  • Comparing two 26-element lists is O(26), a constant, which is what keeps this O(n). Comparing sorted substrings instead would be O(n k log k).

Full Solution — all languages

class Solution:
    def checkInclusion(self, s, t):
        if len(s)>len(t): return False
        need=[0]*26; win=[0]*26
        for c in s: need[ord(c)-97]+=1
        for i,c in enumerate(t):
            win[ord(c)-97]+=1
            if i>=len(s): win[ord(t[i-len(s)])-97]-=1
            if win==need: return True
        return False
Asked at Databricks
SensAI
Beta
Tap the mic to stop voice mode