Solving Leetcode Interviews in Seconds with AI: Permutation in String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "567" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. Example 1: Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input: s1 = "ab", s2 = "eidboaoo" Output: false Constraints: 1 <= s1.length, s2.length <= 104 s1 and s2 consist of lowercase English letters.
Explanation
Here's the breakdown of the approach, followed by the Python code:
- Sliding Window: Use a sliding window of size
len(s1)to traverses2. - Character Frequency Comparison: For each window, compare the character frequencies within the window with the character frequencies of
s1. If they match, a permutation exists. Optimization: Instead of creating a frequency map for each window, maintain a single frequency map and update it as the window slides.
Runtime Complexity: O(n), where n is the length of s2. Storage Complexity: O(1), since the character map size is constant (26 lowercase English letters).
Code
def checkInclusion(s1: str, s2: str) -> bool:
"""
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
"""
if len(s1) > len(s2):
return False
s1_freq = {}
s2_freq = {}
for char in s1:
s1_freq[char] = s1_freq.get(char, 0) + 1
for i in range(len(s1)):
s2_freq[s2[i]] = s2_freq.get(s2[i], 0) + 1
for i in range(len(s2) - len(s1) + 1):
if s1_freq == s2_freq:
return True
if i < len(s2) - len(s1):
s2_freq[s2[i]] -= 1
if s2_freq[s2[i]] == 0:
del s2_freq[s2[i]]
s2_freq[s2[i + len(s1)]] = s2_freq.get(s2[i + len(s1)], 0) + 1
return False