Intuition
The problem involves checking if one of the permutations of string s1 is a substring of string s2. The solution needs to efficiently handle the changing window of length w in string s2 and determine if, at any point, the characters in the window form a permutation of s1.
Approach
The provided solution uses a sliding window approach along with a dictionary (dic) to keep track of the counts of characters in the current window.
Initialize the dictionary dic to store the counts of characters in s1.
Initialize the variable s1count to 1, representing the count of characters in s1.
Iterate through each character in s1 and update the counts in the dictionary.
Iterate through the characters in s2 using the variable i ranging from 0 to len(s2) - 1:
If the current character in s2 is in the dictionary, decrement its count.
If the index i is greater than or equal to the length of s1, increment the count of the character at position i - w if it is in the dictionary.
Check if all values in the dictionary are zero. If true, return True because a permutation of s1 is found in the current window.
If no permutation is found in any window, return False.
Complexity
- Time complexity:
The time complexity of this solution is O(n + n), where len(s1) is the length of string s1 and len(s2) is the length of string s2. The solution iterates through both strings once.
- Space complexity:
The space complexity is O(n), as the dictionary dic stores the counts of characters in s1. The space used is proportional to the size of s1.
Code
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
dic = {}
s1count = 1
w = len(s1)
length = range(len(s2))
for s in s1:
if s in dic:
dic[s] += 1
else:
dic[s] = s1count
for i in length:
if s2[i] in dic:
dic[s2[i]] -= 1
if i >= w and s2[i-w] in dic:
dic[s2[i-w]] += 1
if all(val == 0 for val in dic.values()):
return True
return False