Space
Open
From Fieldwork
Scales
Archive
This approach uses the Sliding Window technique with fixed-size arrays.
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
# Initialize frequency arrays for a-z
s1_count = [0] * 26
s2_count = [0] * 26
# Fill frequency arrays for the first window
for i in range(len(s1)):
s1_count[ord(s1[i]) - ord('a')] += 1
s2_count[ord(s2[i]) - ord('a')] += 1
# Check the very first window
if s1_count == s2_count:
return True
# Slide the window across s2
# i represents the index of the character entering the window
for i in range(len(s1), len(s2)):
# Add the new character to the window
s2_count[ord(s2[i]) - ord('a')] += 1
# Remove the character that just left the window
# The character leaving is at index: i - len(s1)
left_char_idx = i - len(s1)
s2_count[ord(s2[left_char_idx]) - ord('a')] -= 1
# Check if the current window matches s1
if s1_count == s2_count:
return True
return FalsePractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode