Solving Leetcode Interviews in Seconds with AI: Is Subsequence
Introduction
In this blog post, we will explore how to solve the LeetCode problem "392" 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 s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). Example 1: Input: s = "abc", t = "ahbgdc" Output: true Example 2: Input: s = "axc", t = "ahbgdc" Output: false Constraints: 0 <= s.length <= 100 0 <= t.length <= 104 s and t consist only of lowercase English letters. Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
Explanation
Here's the breakdown:
- Two-Pointer Approach: Use two pointers, one for
sand one fort. Iterate throught, and if the character at thetpointer matches the character at thespointer, advance thespointer. - Subsequence Check: If the
spointer reaches the end ofs, it meanssis a subsequence oft. Pre-processing for Follow-up: For many incoming
sstrings, pre-processtto create an index of character positions. This allows for efficient subsequence checking by only considering relevant positions int.Runtime Complexity: O(length of t), Storage Complexity: O(1)
Code
def is_subsequence(s: str, t: str) -> bool:
"""
Checks if s is a subsequence of t.
Args:
s: The potential subsequence.
t: The string to check against.
Returns:
True if s is a subsequence of t, False otherwise.
"""
i = 0 # Pointer for s
j = 0 # Pointer for t
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)
def is_subsequence_preprocessed(s: str, char_index: dict) -> bool:
"""
Checks if s is a subsequence of t using preprocessed character index.
Args:
s: The potential subsequence.
char_index: A dictionary mapping characters in t to their indices.
Returns:
True if s is a subsequence of t, False otherwise.
"""
last_index = -1
for char in s:
if char not in char_index:
return False
found = False
for index in char_index[char]:
if index > last_index:
last_index = index
found = True
break
if not found:
return False
return True
def preprocess_string(t: str) -> dict:
"""
Preprocesses a string t to create an index of character positions.
Args:
t: The string to preprocess.
Returns:
A dictionary mapping characters in t to their indices.
"""
char_index = {}
for i, char in enumerate(t):
if char not in char_index:
char_index[char] = []
char_index[char].append(i)
return char_index
# Example Usage (for the follow-up scenario)
if __name__ == '__main__':
t = "ahbgdc"
char_index = preprocess_string(t)
s1 = "abc"
s2 = "axc"
s3 = "ace"
s4 = "aec"
print(f"'{s1}' is subsequence of '{t}': {is_subsequence_preprocessed(s1, char_index)}") # True
print(f"'{s2}' is subsequence of '{t}': {is_subsequence_preprocessed(s2, char_index)}") # False
print(f"'{s3}' is subsequence of '{t}': {is_subsequence_preprocessed(s3, char_index)}") # True
print(f"'{s4}' is subsequence of '{t}': {is_subsequence_preprocessed(s4, char_index)}") # False