Problem Description
Given two strings s1 and s2, determine if s2 contains any permutation of s1 as a substring. In other words, check if one of s1's rearrangements exists within s2.
Key Insights
- Use a sliding window approach to examine substrings of s2 of length equal to s1.
- Maintain frequency counts of characters for both s1 and the current window in s2.
- Compare the frequency counts to determine if a valid permutation exists.
- Increment the window by adding a new character and removing the leftmost one, keeping the operation efficient.
Space and Time Complexity
Time Complexity: O(n) where n is the length of s2 (each character is processed a constant number of times).
Space Complexity: O(1) since the frequency count arrays have a fixed size (26 for lowercase English letters).
Solution
The solution uses two fixed-length arrays (of size 26) to store character frequencies for s1 and the current window in s2. First, initialize the frequency arrays by processing s1 and the first window of s2. Then, slide the window one character at a time, updating the counts by incrementing the count for the new character and decrementing the count for the character that is no longer in the window. After each move, compare both frequency arrays; if they match, s2 contains a permutation of s1. This technique avoids repeatedly computing the frequency distribution from scratch, making the algorithm efficient.