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).
s
and t
?We can solve this problem using a two-pointer technique where we iterate through the characters of both strings simultaneously. Here’s the step-by-step strategy:
i
for s
and j
for t
, both starting from the beginning (index 0).t
with the pointer j
.
s[i]
equals t[j]
, increment i
.j
irrespective of whether s[i]
matches t[j]
.i
reaches the length of s
before or when j
reaches the end of t
, then all characters of s
have been found sequentially in t
, so return true
.t
is reached and i
is not equal to the length of s
, return false
.n
and m
are the lengths of strings s
and t
respectively. This is because we are iterating through each string at most once.def isSubsequence(s: str, t: str) -> bool:
m, n = len(s), len(t)
i, j = 0, 0
while i < m and j < n:
if s[i] == t[j]:
i += 1
j += 1
return i == m
# Example Usage
print(isSubsequence("abc", "ahbgdc")) # Expected output: True
print(isSubsequence("axc", "ahbgdc")) # Expected output: False
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?