Permutation in String

35 min · checkInclusion()

A shuffled word can hide inside a much longer string without keeping any of its original order.

A permutation is a rearrangement that uses every character exactly as many times as before. Given lowercase strings s1 and s2, return true when some substring — a contiguous stretch — of s2 is a permutation of s1. Otherwise, return false.

Another way to say it: the matching window must have the same character multiset, meaning the same characters with the same frequencies. If s1 is longer than s2, no such window can exist.

A few ground rules:

  • Order inside the matching window doesn't matter.
  • Repeated letters do matter: two copies must be matched by two copies.
  • The window length is always exactly s1.length.

Constraints

  • 1 <= s1.length, s2.length <= 100_000
  • s1 and s2 contain only lowercase English letters a through z.

Hints

Fix the window size

Any permutation of s1 has exactly s1.length characters. You never need to test shorter or longer windows in s2.

Compare frequencies

Build 26 counts for s1. For a candidate window, build the same counts and compare them. This works, but rebuilding for every starting position repeats a lot of work.

Update only two letters

When the window moves right by one position, one character leaves and one enters. Adjust those two counts and track how many of the 26 buckets still match.

Follow-up

Could you return the starting index of the first matching window while keeping the same time and space bounds?

Visible cases

Examples

Example 1

ready
Input
s1 = "ab"
s2 = "eidbaooo"
Expected
true
Why
the window 'ba' uses one 'a' and one 'b'

Example 2

ready
Input
s1 = "ab"
s2 = "eidboaoo"
Expected
false
Why
no two-character window has both required letters

Example 3

ready
Input
s1 = "adc"
s2 = "dcda"
Expected
true
Why
the ending window 'cda' rearranges all three letters

Interview signal

Asked at

AmazonMicrosoftMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite