392. Is Subsequence
On This Page
Problem Statement
Given two strings s
and t
, you need to determine if s
is a subsequence of t
. To be a subsequence, you can remove characters from t
without reordering to form s
.
Naive Solution
The naive approach would be to generate all subsequences of string t
and then check if string s
is one of them. However, generating all subsequences of t
can be computationally expensive especially when the length of t
is large.
Hints & Tips
Understanding the nature of the problem is vital. This problem can be visualized as two pointers moving through both strings. If characters match, move both pointers. If not, only move the pointer in t
.
Approach
To determine if s
is a subsequence of t
, we can use a two-pointer technique.
- Begin by initializing two pointers at the start of
s
andt
. - Move through
t
, looking for a match with the current character ofs
. - If you find a match, move to the next character in
s
. - If you reach the end of
s
while doing this, it meanss
is a subsequence oft
.
Steps
- Initialize two pointers
i
andj
to 0.i
points to characters ins
whilej
points to characters int
. - Traverse through
t
using the pointerj
. - When
s[i]
is equal tot[j]
, incrementi
. - If
i
becomes equal to the length ofs
, return True since it means all characters ofs
are present int
in order. - If the loop completes and
i
is not equal to the length ofs
, return False.
Solution
def isSubsequence(s, t):
# Initialize two pointers at the start of the strings.
i, j = 0, 0
while j < len(t):
# If the current characters match, move to the next character in s.
if i < len(s) and s[i] == t[j]:
i += 1
j += 1
# If all characters in s were found in t, return True.
return i == len(s)