LeetCode #567 Medium

Permutation in String

Permutation in String is LeetCode 567 (Medium). Given two strings s1 and s2, return true if some rearrangement of s1 appears in s2 as a block of consecutive letters, and false otherwise.

  • A rearrangement keeps every letter of s1 the same number of times, so only letter counts matter, not order.
  • Both strings use lowercase letters only and can be 10⁴ letters long.
  • If s1 is longer than s2, no block of s2 is long enough, and the answer is false.
Constraints
  • 1 <= s1.length, s2.length <= 10⁴
  • s1 and s2 consist of lowercase English letters.
stringsliding-windowhash-table
Open on LeetCode ↗
02

Intuition

Only blocks of s2 exactly as long as s1 can be rearrangements of it, and two neighbouring blocks differ by one letter at each end. So slide a window of length len(s1) across s2.

Keep need[c] = (count of c in s1) − (count of c in the window). Positive means the window is short of c; negative means it has extra. Instead of checking all 26 letters at every step, keep one number, off, the total of how far each letter is from zero. A letter entering or leaving changes one entry of need by one, so off moves by exactly one, and the window is a rearrangement of s1 exactly when off is 0.

How to spot this pattern

"Does any block of length k have the same letters as a pattern?" is a fixed-length window over letter counts. When you only need a yes/no, one running mismatch number replaces comparing whole count arrays.

03

Approach

Try it first

Before reading on, take a window that is short one a. Decide how one number should change when an a enters, and when a b the window already had too many of leaves. Aim for O(n) time with O(1) work per step.

1

Count what the window owes

Fill need with the letter counts of s1 and set off = len(s1). An empty window is short of every letter of s1, so the total distance from a match is the length of s1.

2

Let a letter enter

For each new letter c of s2: if need[c] > 0 the window was short of c, so off drops by 1; otherwise c is an extra, so off grows by 1. Then decrease need[c].

3

Let a letter leave

Once the window would be longer than s1, remove the letter len(s1) places back: increase need for it, then add 1 to off if that letter is now owed, or subtract 1 if it was an extra. The window stays exactly len(s1) letters long.

4

Check the counter

After both moves, off == 0 means every letter count matches s1, so return true right away. If the window reaches the end of s2 without that happening, return false.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def checkInclusion(self, s1: str, s2: str) -> bool:
▶3 k = len(s1)
▶4 need = Counter(s1)
▶5 off = k
▶6 for i, c in enumerate(s2):
▶7 off += -1 if need[c] > 0 else 1
▶8 need[c] -= 1
▶9 if i >= k:
▶10 old = s2[i - k]
▶11 need[old] += 1
▶12 off += 1 if need[old] > 0 else -1
▶13 if off == 0:
▶14 return True
▶15 return False
s2e0i1d2b3a4o5o6o7oweda1b1d0e0i0o0off2letters away from a matchempty window owes “ab”: off is 2
k2
off2
The window is empty, so it is short of every letter of “ab”. Adding up how far each letter is from matching gives 2, the length of s1.
s2e0i1d2b3a4o5o6o7oweda1b1d0e−1i0o0off3letters away from a match“e” enters: an extra, off up to 3
ine
owed e-1
off3
“e” is not in s1 at all, so this letter is an extra and moves the window one step further from matching.
s2e0i1d2b3a4o5o6o7oweda1b1d0e−1i−1o0off4letters away from a match“i” enters: an extra, off up to 4
ini
owed i-1
off4
“i” is not in s1 at all, so this letter is an extra and moves the window one step further from matching.
s2e0i1d2b3a4o5o6o7oweda1b1d−1e−1i−1o0off5letters away from a match“d” enters: an extra, off up to 5
ind
owed d-1
off5
“d” is not in s1 at all, so this letter is an extra and moves the window one step further from matching.
s2e0i1d2b3a4o5o6o7oweda1b1d−1e0i−1o0off4letters away from a match“e” leaves: it was extra, off down to 4
oute
owed e0
off4
The window may hold only 2 letters, so “e” at index 0 leaves. It was surplus, so losing it brings the window closer to a match.
s2e0i1d2b3a4o5o6o7oweda1b0d−1e0i−1o0off3letters away from a match“b” enters: it was owed, off down to 3
inb
owed b0
off3
The window was short of “b”, so this letter closes one gap and the window is one step closer to matching.
s2e0i1d2b3a4o5o6o7oweda1b0d−1e0i0o0off2letters away from a match“i” leaves: it was extra, off down to 2
outi
owed i0
off2
The window may hold only 2 letters, so “i” at index 1 leaves. It was surplus, so losing it brings the window closer to a match.
s2e0i1d2b3a4o5o6o7oweda0b0d−1e0i0o0off1letters away from a match“a” enters: it was owed, off down to 1
ina
owed a0
off1
The window was short of “a”, so this letter closes one gap and the window is one step closer to matching.
s2e0i1d2b3a4o5o6o7oweda0b0d0e0i0o0off0letters away from a match“d” leaves: it was extra, off down to 0
outd
owed d0
off0
The window may hold only 2 letters, so “d” at index 2 leaves. It was surplus, so losing it brings the window closer to a match.
s2e0i1d2b3a4o5o6o7oweda0b0d0e0i0o0off0letters away from a match“ba” uses the letters of “ab” → true
returntrue
Every letter count in the window equals its count in s1, so this block is a rearrangement of s1. The search stops at the first one.
05

Common pitfalls

Updating the leaving letter in the wrong order

✗ Wrong
off += 1 if need[old] > 0 else -1
need[old] += 1
✓ Right
need[old] += 1
off += 1 if need[old] > 0 else -1

The test must look at the count after the letter has gone. For s1 = "ab", s2 = "bxa" the b leaves while its count is exactly right. Tested too early, it lowers off to 0 instead of raising it, and the code returns true for the window "xa".

06

Edge cases

s1 longer than s2, like s1 = "abc", s2 = "ab"

The window never holds all three letters, so off stays above 0 and the loop ends with false. No separate length check is needed.

07

Complexity

Time
O(len(s1) + len(s2))
Space
O(1)
Counting s1 takes one pass, and each letter of s2 enters once and leaves once, each move costing a constant number of steps. The counts cover at most 26 letters, whatever the string lengths.
08

Permutation in String FAQ

How is this different from Find All Anagrams in a String?

It is the same window, but Find All Anagrams in a String needs every starting index, while this problem needs only a yes/no and can stop at the first match. That page compares two count arrays; the mismatch counter here is a way to make each check a single comparison.

Why not generate every permutation of s1 and search for each?

s1 can have 10⁴ letters, and even 10 distinct letters already give 3,628,800 orders. Counting letters makes the order irrelevant, which is exactly what "any permutation" means.

Does it work for uppercase or Unicode text?

In Python, Counter works for any characters unchanged. In C++ and Java, swap the 26-slot array for a hash map keyed by character; the counter logic stays the same.