Given two strings
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.,
Output: true
Explanation: "abc" letters can be found at 0, 2 and 5th index positions in "ahbgdc"
Output: false
Explanation: "axc" is not a subsequence for "ahbgdc" since "x" is not present at all.
Output: false
Explanation: "axc" is not a subsequence for "ahbgdcx", because even though the letters are present but they are not in the sequence.
Contents
Solution using two pointers
In this approach, we are going to use two pointers one pointer to point at input string
-
We will create a function
usingTwoPointers that takes input arguments strings andt . -
Base case is, if the length of
s is greater than length oft , then we can simply returnfalse . -
We will create two pointers
i andj to track indexes in stringss andt respectively. -
Then, we will check characters from each string until
i andj did not go out of bounds ofs andt .-
If characters at
i th index ins is same as character atj th index int , then we will incrementi andj . Since we found a matching charcater, we can continue checking next remaining characters. -
Otherwise, just increment
j to see if character ins may appear at later index int .
-
If characters at
-
Finally, at the end check if
i reached end index of strings or not, if it reached thens is a subsequence oft , otherwise not.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1) since we are using just indexes
Above implementations source code can be found at