567. Permutation in String¶
Intuition¶
The task is to determine if one of the permutations of the string s1 is present as a substring in s2. To achieve this, we use a sliding window approach that compares character frequencies between the current window of s2 and s1.
Approach: Counting + Sliding Window¶
We maintain a frequency array (freq[26]) that tracks the difference in character counts between the current window in s2 and the string s1. A key idea is that if all character frequencies match (i.e., their differences are zero), the current window of s2 contains a permutation of s1.
Explanation:¶
- Initial Setup:
- We first check if the length of
s1is greater thans2. Ifs1is longer, it's impossible for a permutation ofs1to be ins2, so we returnfalse. - We initialize
freq[26]to store the frequency difference betweens1and the first window (substring) ofs2of lengthn(length ofs1). diffCountkeeps track of how many characters have non-zero frequency differences betweens1and the current window ins2.- Processing the First Window:
- For the first
ncharacters ofs2, we decrement the frequency for the characters ofs1and increment it for the corresponding characters ofs2. - We update
diffCountbased on the frequency values. If a frequency changes from zero to non-zero or vice versa,diffCountis adjusted accordingly. - Sliding the Window:
- For each subsequent character in
s2(starting from indexn), we update the window by removing the effect of the character that is sliding out (at indexi - n) and adding the effect of the new character (at indexi). - After adjusting the frequencies, we check if
diffCountis zero, which indicates that the current window matches a permutation ofs1. - Termination:
- If at any point
diffCountbecomes zero, we returntrue. - If we finish sliding through
s2without finding a valid window, we returnfalse.
Complexity¶
- Time complexity: O(m), where
mis the length ofs2. We perform constant-time updates on the frequency array for each character ins2. - Space complexity: O(d), where
dis the number of distinct characters (in this case,d = 26for lowercase English letters).
Code¶
int freq[26];
class Solution {
public:
bool checkInclusion(string& s1, string& s2) {
int n = s1.size(), m = s2.size();
if (n > m) return false;
memset(freq, 0, sizeof(freq));
int diffCount = 0;
for (size_t i = 0; i < n; i++) {
diffCount += (freq[s1[i] - 'a'] == 0) - (--freq[s1[i] - 'a'] == 0);
diffCount += (freq[s2[i] - 'a'] == 0) - (++freq[s2[i] - 'a'] == 0);
}
if (diffCount == 0) return true;
for (size_t i = n; i < m; i++) {
diffCount += (freq[s2[i - n] - 'a'] == 0) - (--freq[s2[i - n] - 'a'] == 0);
diffCount += (freq[s2[i] - 'a'] == 0) - (++freq[s2[i] - 'a'] == 0);
if (diffCount == 0) return true;
}
return false;
}
};