Skip to content
Back to notes
Oct 22, 2026
Medium

Permutation in String

"does s2 contain a permutation / anagram of s1?" → fixed-size sliding window of len(s1) + letter counts. "Any order" means compare counts; "substring" means a contiguous window of a known length. When the window moves, one character comes in and one goes out: update those two counts and never recount the window. Compare with a 26-element list ==, or keep a missing counter for O(1).
  • string
  • hash map
  • sliding window

Problem

You are given two strings s1 and s2.

Return true if s2 contains a permutation of s1, or false otherwise. That means if a permutation of s1 exists as a substring of s2, then return true.

Both strings only contain lowercase letters.

Example 1

Input:  s1 = "abc", s2 = "lecabee"
Output: true

The substring "cab" is a permutation of "abc" and is present in "lecabee".

Example 2

Input:  s1 = "abc", s2 = "lecaabee"
Output: false

Constraints

  • 1 <= len(s1), len(s2) <= 10,000
  • Both strings consist of lowercase English letters.

Thinking

  • Brute force idea: generate every permutation of s1 and search for it (O(m!)O(m!), hopeless), or check every window of s2 by sorting it (O(n⋅mlog⁡m)O(n \cdot m \log m)) or counting it (O(n⋅m)O(n \cdot m)), where m=m = len(s1) and n=n = len(s2).
  • Key insight: “a permutation of s1” means the same letter counts as s1, and so the same length. Only windows of exactly m characters can match, so this is a fixed-size sliding window. Moving the window one step changes exactly two counts: +1 for s2[r] coming in and -1 for s2[r - m] going out. Update those in O(1)O(1) instead of recounting the window, then compare with s1’s counts: O(26)O(26) with two 26-element arrays, or O(1)O(1) if you keep a running count of how many letters the window is still missing.
  • There are n - m + 1 windows, starting at 0 .. n - m. A start past n - m gives a slice shorter than s1, which can never match.
  • Quick reject: len(s1) > len(s2) means False.
  • Edge cases to remember: s1 longer than s2; same length (the only window is all of s2); the match at the very start or the very end (the last window must be checked); the right letters with the wrong counts (example 2, "caab"); letters in s2 that aren’t in s1; a single character; repeated letters in s1.

Solution

Approach A — mine: recount every window with Counter

Complexity: Time O(n⋅m)O(n \cdot m) · Space O(m)O(m)

Correct, and the idea is right: compare letter counts, not orders. The cost is that it builds a new Counter from scratch for every start. s2[l:r] copies m characters and Counter reads all of them, even though the next window shares m - 1 of them. The loop also runs l over all of range(len(s2)): for l > n - m the slice is shorter than s1 and can never match. With len(s1) == len(s2) only the first window is real, and the other n - 1 iterations recount about n2/2n^2 / 2 characters for nothing, which makes that the worst input (see Scratch). Small things: r = 0 is never used, and Counter(s1) is built before the early return.

from collections import Counter


def check_inclusion_mine(s1: str, s2: str) -> bool:
    count = Counter(s1)
    if len(s1) > len(s2):
        return False
    r = 0  # unused: overwritten on the first iteration
    for l in range(len(s2)):  # windows starting after len(s2) - len(s1) are too short to match
        r = l + len(s1)
        count_s2 = Counter(s2[l:r])  # O(m): copies and recounts the whole window every step

        if count_s2 == count:
            return True
    return False

Approach B — slide the Counter (smallest fix to A)

Complexity: Time O(26⋅n)O(26 \cdot n) · Space O(26)O(26)

Build the window’s Counter once, then on each step add s2[r] and remove s2[r - m]. Removing can leave a key with count 0; since Python 3.10, Counter.__eq__ treats a zero count the same as a missing key, so the comparison still works (before 3.10 you had to del those keys). The catch: Counter.__eq__ is written in Python (a generator over both key sets), so every comparison costs dozens of Python-level steps.

def check_inclusion_counter(s1: str, s2: str) -> bool:
    m = len(s1)
    if m > len(s2):
        return False
    need = Counter(s1)
    window = Counter(s2[:m])
    if window == need:
        return True
    for r in range(m, len(s2)):  # slide: s2[r] comes in, s2[r - m] goes out
        window[s2[r]] += 1
        window[s2[r - m]] -= 1  # may leave a 0 count; == ignores those (Python 3.10+)
        if window == need:  # Python-level loop over the keys
            return True
    return False

Approach C — one count map + missing counter (true O(n)O(n))

Complexity: Time O(n)O(n) · Space O(26)O(26)

need[c] is how many more c the window needs (negative means it has extra), and missing is how many characters of s1 the window doesn’t cover yet. A character coming in lowers missing only if it was still needed; a character going out raises it only if it’s needed again. When missing == 0 the window has at least s1’s count of every letter and has length m, so it’s exactly a permutation. Checking before the window is full is safe: missing >= m - window_len > 0 there. No 26-way compare, so it works for any alphabet, and it’s the same bookkeeping as Minimum Window Substring (#76). The follow-up answer if you’re asked to drop the factor of 26.

def check_inclusion_missing(s1: str, s2: str) -> bool:
    m = len(s1)
    if m > len(s2):
        return False
    need = Counter(s1)  # need[c] = how many more c the window needs (< 0: extra)
    missing = m  # characters of s1 the window doesn't cover yet
    for r, c in enumerate(s2):
        if need[c] > 0:  # c was still needed
            missing -= 1
        need[c] -= 1
        if r >= m:  # window is m + 1 long: drop s2[r - m]
            out = s2[r - m]
            need[out] += 1
            if need[out] > 0:  # out is needed again
                missing += 1
        if missing == 0:  # length m and covers s1: a permutation
            return True
    return False

Approach D — fixed-size window + two 26-count arrays ✅ best practice

Complexity: Time O(26⋅n)=O(n)O(26 \cdot n) = O(n) · Space O(26)O(26)

The interview-standard version and the one to remember. Keep the counts in two fixed lists indexed by ord(c) - ord("a"). Each step is two updates and one window == need. That list comparison runs in C and stops at the first count that differs, so it’s the simplest version to write and also the fastest here, even though C has the better bound.

def check_inclusion(s1: str, s2: str) -> bool:
    m, n = len(s1), len(s2)
    if m > n:
        return False
    a = ord("a")
    need, window = [0] * 26, [0] * 26
    for c in s1:
        need[ord(c) - a] += 1
    for c in s2[:m]:
        window[ord(c) - a] += 1
    if window == need:
        return True
    for r in range(m, n):  # slide: s2[r] comes in, s2[r - m] goes out
        window[ord(s2[r]) - a] += 1
        window[ord(s2[r - m]) - a] -= 1
        if window == need:  # 26-element compare, runs in C
            return True
    return False

Scratch / Experiments

Two inputs at the max length n=10,000n = 10{,}000, neither with a match, so every approach scans to the end:

  • m = 5,000, random letters: m=n/2m = n/2 is the most work for a correct n - m + 1 loop ((n−m+1)⋅m≈25(n - m + 1) \cdot m \approx 25 million characters counted).
  • m = n: "aaa…ab" in "aaa…a". There’s only one real window, so the sliding versions just count each string once and stop, but A’s loop keeps going over the shrinking tail.

Measured (m = 5,000): two arrays (D) ~1.0 ms, missing counter (C) ~1.9 ms, sliding Counter (B) ~2.5 ms, mine (A) ~0.7 s (~700× slower than D). On m = n, A takes ~1 s against ~0.8 ms for D. That’s more than on the first input even though there’s only one real window: the n - 1 too-short tail windows recount about n2/2=50n^2 / 2 = 50 million characters.

D is O(26⋅n)O(26 \cdot n) and still beats C’s O(n)O(n) by about 2×. D’s window == need is one C-level comparison that stops at the first count that differs (on random text that’s within the first few letters), while C runs several Python-level operations per character for its ifs and Counter lookups. B has the same bound as D, but Counter.__eq__ is a Python generator, so it’s the slowest of the sliding versions. A’s per-character work is cheap (Counter counts in C), but ~37 million characters on the first input and ~50 million on the second still add up to most of a second. Big-O hides constants, and in Python the constant that matters is how many Python-level steps run per character.

import random
import string

rng = random.Random(0)
s2 = "".join(rng.choice(string.ascii_lowercase) for _ in range(10_000))
s1 = "".join(rng.choice(string.ascii_lowercase) for _ in range(5_000))
same_s1, same_s2 = "a" * 9_999 + "b", "a" * 10_000  # len(s1) == len(s2), no match

assert not any(fn(s1, s2) for fn in FNS)
assert not any(fn(same_s1, same_s2) for fn in FNS)
%timeit -n 1 -r 3 check_inclusion_mine(s1, s2)
%timeit check_inclusion_counter(s1, s2)
%timeit check_inclusion_missing(s1, s2)
%timeit check_inclusion(s1, s2)
%timeit -n 1 -r 3 check_inclusion_mine(same_s1, same_s2)
%timeit check_inclusion(same_s1, same_s2)

Takeaways

  • Pattern: “does s2 contain a permutation / anagram of s1?” → fixed-size sliding window of len(s1) + letter counts. “Any order” means compare counts; “substring” means a contiguous window of a known length. When the window moves, one character comes in and one goes out: update those two counts and never recount the window. Compare with a 26-element list ==, or keep a missing counter for O(1)O(1).
  • Mistakes I made:
    • Rebuilt Counter(s2[l:r]) for every window: O(m)O(m) per step, O(n⋅m)O(n \cdot m) total, even though neighboring windows share m - 1 characters. When a window moves by one, only two counts change.
    • Looped l over range(len(s2)) instead of range(len(s2) - len(s1) + 1). The last len(s1) - 1 windows are shorter than s1 and can never match. With len(s1) == len(s2) that wasted tail is the whole cost (about a second instead of under a millisecond). A string of length n has n - m + 1 windows of length m.
    • Left a dead r = 0, and built Counter(s1) before the early return.
  • Related problems: Valid Anagram (#242, the one-window version: compare counts); Find All Anagrams in a String (#438, this exact window, but collect every start index instead of returning True); Minimum Window Substring (#76, the variable-size version of Approach C’s missing counter); Longest Repeating Character Replacement (#424, variable-size window with letter counts); Group Anagrams (#49, letter counts as a dictionary key); Sliding Window Maximum (#239, fixed-size window with harder state to keep).