Skip to content
Problem 567 · LeetCode 567(opens in a new tab)

Permutation in String

MediumHash tables

You are given two strings of lower-case letters, s1 and s2. Decide whether some block of consecutive letters in s2 uses exactly the letters of s1, each the same number of times, in any order.

Return true if such a block exists and false if it does not. The block must be unbroken: letters of s1 that are spread out across s2 do not count.

Example 1

Input:  s1 = "abc", s2 = "xbcaz"
Output: true
Why:    "bca" is a reordering of "abc"
2 more examples and the constraints

Example 2

Input:  s1 = "pq", s2 = "pxq"
Output: false
Why:    p and q are both there, but never side by side

Example 3

Input:  s1 = "abcd", s2 = "abc"
Output: false
Why:    s2 is shorter than s1

Constraints

  • 1 ≤ length of s1 ≤ 10,000
  • 1 ≤ length of s2 ≤ 10,000
  • Both strings use only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort every windowO(m·n log n)
  2. Sliding window of letter countsO(m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for two strings of 10,000 lettersVerdict
Sort every windowO(m·n log n)
Mention it, then move on
Sliding window of letter countsO(m)
Best; two updates per move

n = length of s1, m = length of s2.

Edge cases to test

  • s1 longer than s2. No window fits, so the answer is false. Check that your loop bounds do not go negative.
  • Repeated letters. "aab" needs two a's in the window; a window with one a and two b's must not match.
  • Match at the very end. The last window of s2 can be the answer, so compare after the final update.
  • Letters present but apart. "pq" in "pxq" is false: the letters must be next to each other.

Common mistakes

  • Comparing before removing the letter that left, so the window is one letter too long.
  • Checking only that every letter of s1 appears, not how many times.
  • Rebuilding the counts for every window, which brings back the slow approach.

How to talk through it

  1. 1Clarify. Only lower-case letters? Must the block be contiguous? What if s1 is longer than s2?
  2. 2Give the brute force. Sort every window of length n and compare with sorted s1; say why repeating that work is slow.
  3. 3Name the invariant. A rearrangement has the same letter counts. A window that slides changes only two counts.
  4. 4Code the window. Add the new letter, drop the old one once the window is full, then compare the 26 counts.
  5. 5Test out loud. Run a match at the end, repeated letters, and s1 longer than s2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?