Problem
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
OR
Given two strings str1 and str2, find if str1 is a subsequence of str2.
Subarrays vs Subsequences vs Subsets Definition
Follow up
- Expected time complexity is linear.
- Suppose there are lots of incoming
s, says1, s2, ..., skwherek >= 109, and you want to check one by one to see ifthas its subsequence. In this scenario, how would you change your code?
Examples
Example 1:
| |
Example 2:
| |
Constraints
0 <= s.length <= 1000 <= t.length <= 10^4sandtconsist only of lowercase English letters.
Solution
The idea is simple, we traverse both strings from one side to other side (say from rightmost character to leftmost). If we find a matching character, we move ahead in both strings. Otherwise we move ahead only in str2.
Method 1 - Recursion
Following is Recursive Implementation of the above idea.
Code
| |
Complexity
- ⏰ Time complexity:
O(n)wherenis length of stringt - 🧺 Space complexity:
O(n)- Assuming recursion stack
Method 2 - Iterative with 2 pointer technique
To determine if string s is a subsequence of string t, we can use a two-pointer method:
- Initialize two pointers
iandjto 0, whereiwill traversesandjwill traverset. - Iterate through the characters of
tusingj. - If the current character in
t(pointed byj) matches the current character ins(pointed byi), move the pointerito the next character. - Regardless of whether there’s a match, increment
jto check the next character int. - If
ireaches the length ofs, all characters ofshave been found intin sequence, and we returntrue. - If the loop ends and
ihas not reached the length ofs, returnfalse.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n)wherenis the length oft. We potentially traverse all characters oft. - 🧺 Space complexity:
O(1). We only use a constant amount of extra space for the pointers.
Method 3 - Iterative
The idea is simple, we traverse both strings from one side to another side (say from rightmost character to leftmost). If we find a matching character , we move ahead in both strings. Otherwise, we move ahead only in t.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)