419/670

419. Permutation in String

Medium

You get two strings s1 and s2, both made of lowercase English letters. Decide whether s2 contains a permutation of s1: a contiguous block of s2 whose letters can be rearranged to spell s1 exactly.

Return true if such a block exists anywhere in s2, and false otherwise.

Note that the block must be contiguous — scattered letters don't count — but the order of letters inside it is free.

Example 1:

Input: s1 = "ab", s2 = "eidbaooo"

Output: true

Explanation: The substring "ba" (characters 3–4 of s2) rearranges to "ab".

Example 2:

Input: s1 = "ab", s2 = "eidboaoo"

Output: false

Explanation: s2 contains both an 'a' and a 'b', but never side by side, and the block must be contiguous.

Example 3:

Input: s1 = "abc", s2 = "ccbbaa"

Output: false

Explanation: Every length-3 window ("ccb", "cbb", "bba", "baa") has a doubled letter, so none matches one 'a', one 'b', one 'c'.

Constraints:

  • 1 ≤ s1.length, s2.length ≤ 10⁴
  • s1 and s2 consist of lowercase English letters only

Hints:

Two strings are permutations of each other exactly when their letter counts agree — order is irrelevant. So you're hunting for a window of s2 of length |s1| whose 26-letter histogram equals s1's.

Every candidate window has the same fixed length. Slide it one position at a time: one letter enters on the right, one leaves on the left. Update two counter entries instead of recounting the whole window.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s1 = "ab", s2 = "eidbaooo"

Expected output: true