Problem
You are given two strings
s1ands2.Return
trueifs2contains a permutation ofs1, orfalseotherwise. That means if a permutation ofs1exists as a substring ofs2, then returntrue.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
s1and search for it (, hopeless), or check every window ofs2by sorting it () or counting it (), wherelen(s1)andlen(s2). - Key insight: “a permutation of
s1” means the same letter counts ass1, and so the same length. Only windows of exactlymcharacters can match, so this is a fixed-size sliding window. Moving the window one step changes exactly two counts:+1fors2[r]coming in and-1fors2[r - m]going out. Update those in instead of recounting the window, then compare withs1’s counts: with two 26-element arrays, or if you keep a running count of how many letters the window is still missing. - There are
n - m + 1windows, starting at0 .. n - m. A start pastn - mgives a slice shorter thans1, which can never match. - Quick reject:
len(s1) > len(s2)meansFalse. - Edge cases to remember:
s1longer thans2; same length (the only window is all ofs2); 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 ins2that aren’t ins1; a single character; repeated letters ins1.
Solution
Approach A — mine: recount every window with Counter
Complexity: Time · Space
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 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 · Space
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 )
Complexity: Time · Space
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 · Space
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 , neither with a match, so every approach scans to the end:
m = 5,000, random letters: is the most work for a correctn - m + 1loop ( 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
million characters.
D is and still beats C’s 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
s2contain a permutation / anagram ofs1?” → fixed-size sliding window oflen(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 amissingcounter for . - Mistakes I made:
- Rebuilt
Counter(s2[l:r])for every window: per step, total, even though neighboring windows sharem - 1characters. When a window moves by one, only two counts change. - Looped
loverrange(len(s2))instead ofrange(len(s2) - len(s1) + 1). The lastlen(s1) - 1windows are shorter thans1and can never match. Withlen(s1) == len(s2)that wasted tail is the whole cost (about a second instead of under a millisecond). A string of lengthnhasn - m + 1windows of lengthm. - Left a dead
r = 0, and builtCounter(s1)before the early return.
- Rebuilt
- 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’smissingcounter); 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).