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.
1from collections import defaultdict
2
3class Solution:
4 def checkInclusion(self, s1: str, s2: str) -> bool:
5 if len(s1) > len(s2):
6 return False
7 count1 = defaultdict(int)
8 count2 = defaultdict(int)
9 for ch in s1:
10 count1[ch] += 1
11 for ch in s2[:len(s1)]:
12 count2[ch] += 1
13 matches = 0
14 for key in count1:
15 if count1[key] == count2[key]:
16 matches += 1
17 l = 0
18 for r in range(len(s1), len(s2)):
19 if matches == len(count1):
20 return True
21 new_char = s2[r]
22 count2[new_char] += 1
23 if count2[new_char] == count1[new_char]:
24 matches += 1
25 elif count2[new_char] == count1[new_char] + 1:
26 matches -= 1
27
28 old_char = s2[l]
29 count2[old_char] -= 1
30 if count2[old_char] == count1[old_char]:
31 matches += 1
32 elif count2[old_char] == count1[old_char] - 1:
33 matches -= 1
34 l += 1
35 return matches == len(count1)
This Python solution optimizes character comparison by leveraging a hash map to keep track of character frequency changes as the sliding window moves. Instead of full map comparison for each slide, it increments and decrements values while checking conditions, which reduces the overhead of comparing full data structures.