The main idea is to use a sliding window technique to compare the character frequency of a substring of s2 with the character frequency of s1. If they match, it means s2 contains a permutation of s1.
Time Complexity: O(n), where n is the length of s2, as each character in s2 is processed once.
Space Complexity: O(1), as the frequency arrays have a fixed size of 26.
1var checkInclusion = function(s1, s2) {
2 if (s1.length > s2.length) return false;
3 const count1 = new Array(26).fill(0);
4 const count2 = new Array(26).fill(0);
5 for (let i = 0; i < s1.length; i++) {
6 count1[s1.charCodeAt(i) - 97]++;
7 count2[s2.charCodeAt(i) - 97]++;
8 }
9 for (let i = s1.length; i < s2.length; i++) {
10 if (arraysEqual(count1, count2)) return true;
11 count2[s2.charCodeAt(i) - 97]++;
12 count2[s2.charCodeAt(i - s1.length) - 97]--;
13 }
14 return arraysEqual(count1, count2);
15};
16
17function arraysEqual(a, b) {
18 for (let i = 0; i < a.length; i++) {
19 if (a[i] !== b[i]) return false;
20 }
21 return true;
22}
Similar to the other solutions, this JavaScript solution uses arrays to hold character counts and a helper function arraysEqual to compare them while sliding the window over s2.
Leverage a hash map (or dictionary) to record the character count of s1 and use it to compare with segments of s2. This approach focuses on incremental updates to the map as the window slides over s2.
Time Complexity: O(n), where n is the length of s2.
Space Complexity: O(1), since the hash map's size is bounded by the character set size of 26.
1var checkInclusion = function(s1, s2) {
2 let len1 = s1.length, len2 = s2.length;
3 if (len1 > len2) return false;
4 const count1 = {}, count2 = {};
5 for (let i = 0; i < len1; i++) {
6 count1[s1[i]] = (count1[s1[i]] || 0) + 1;
7 count2[s2[i]] = (count2[s2[i]] || 0) + 1;
8 }
9 let matches = 0;
10 for (let key in count1) {
11 if (count1[key] === count2[key]) matches++;
12 }
13 for (let i = len1; i < len2; i++) {
14 if (matches === Object.keys(count1).length) return true;
15 let inChar = s2[i];
16 count2[inChar] = (count2[inChar] || 0) + 1;
17 if (count1[inChar] === count2[inChar]) matches++;
18 else if (count1[inChar] + 1 === count2[inChar]) matches--;
19
20 let outChar = s2[i - len1];
21 count2[outChar]--;
22 if (count1[outChar] === count2[outChar]) matches++;
23 else if (count1[outChar] - 1 === count2[outChar]) matches--;
24 }
25 return matches === Object.keys(count1).length;
26};
This JavaScript solution adopts a similar strategy to the Python solution using objects to store character counts and keeps a running number of matched frequencies, sliding the window across s2.