Is Subsequence
String, Two Pointers
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:
Example 2:
Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s
andt
consist only of lowercase English letters.
Solutions
Approach - Two Pointers Technique
This algorithm checks if string s
is a subsequence of string t
. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Steps
Initialize two pointers
i
andj
to 0.i
is used to traverse strings
andj
is used to traverse stringt
. Also, initialize a counterfound
to 0 which keeps track of the number of characters ofs
found int
.Start a
while
loop that continues as long asi
is less than the length ofs
andj
is less than the length oft
.Inside the loop, check if the
j
-th character oft
is equal to thei
-th character ofs
. If it is, increment bothi
andfound
.Regardless of whether the characters match, increment
j
to move to the next character int
.After the loop ends, check if
found
is equal to the length ofs
. If it is, returntrue
, indicating thats
is a subsequence oft
. If not, returnfalse
.
Complexity
Time complexity: O(n) where
n
is the length oft
string.Space complexity: O(1)
Last updated