AceYourInterviews
Checking sign-in…

23. Permutation in String

IntermediateFixed-length frequency differences

Determine whether some continuous part of the text contains exactly the pattern's letters with exactly the same occurrence counts. The letters may appear in any order within that part.

Matching letters scattered across the text is not enough. The candidate substring must have the same length as the pattern.

Example 1

Input

pattern="ab", text="eidbaooo"

Output

true

Explanation: The window ba is a permutation of ab.

Example 2

Input

pattern="aab", text="abab"

Output

true

Explanation: The first window aba contains two a occurrences and one b.

Constraints

  • 0 <= pattern.length, text.length <= 105
  • Both strings contain only lowercase English letters a–z. An empty pattern is permitted.
Hints
Hint 1

What information survives a permutation?

Hint 2

Keep pattern counts minus current-window counts.

Hint 3

Track nonzero slots and test only after reaching exactly the pattern length.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Evict and enter until ba matches

"ab"
"eidbaooo"
true