567. Permutation in String
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Example 2:
- 1 <= s1.length, s2.length <= 104
- s1 and s2 consist of lowercase English letters.
Constraints:
Notes
Intuition
A permutation of s1 in s2 means a substring of s2 has the exact same character frequencies as s1. Slide a fixed-size window across s2 and check if frequencies match.
Implementation
Use a single frequency array. First, increment for each character in s1, then decrement for the first len(s1) characters of s2. If all zeros, we found a match. Slide the window: increment the count of the character leaving (left), decrement the count of the character entering (right). Check for all zeros at each position.
Edge-cases
Return early if len(s1) > len(s2). Don't forget to check for a match after the final window position (after the loop exits).
- Time: O(n) — single pass through s2
- Space: O(1) — frequency array is fixed at 26 elements