Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, one of s1’s permutations is the substring of s2.
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
s1 be longer than s2?
s1 would not fit in s2 if s1 is longer than s2.s1 and s2 are empty?
1 <= s1.length, s2.length.To determine if any permutation of s1 is a substring of s2, we can use the sliding window technique along with character frequency counts:
s1.s1 and count the frequency of characters in this window within s2.s2 and compare the frequency count of the current window to the frequency count of s1.true.s2 without a match, return false.s2 is processed a constant number of times, the time complexity should be linear, (O(N)), where (N) is the length of s2.Let’s implement the described approach:
def checkInclusion(s1: str, s2: str) -> bool:
from collections import Counter
len1, len2 = len(s1), len(s2)
if len1 > len2:
return False
s1_count = Counter(s1)
window_count = Counter(s2[:len1])
if s1_count == window_count:
return True
for i in range(len1, len2):
window_count[s2[i]] += 1
window_count[s2[i - len1]] -= 1
if window_count[s2[i - len1]] == 0:
del window_count[s2[i - len1]]
if s1_count == window_count:
return True
return False
s2. The sliding window process each character constant times.By following this strategy and implementing the sliding window approach, we ensure an efficient solution to the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?