Is Subsequence
Is Subsequence
Problem Statement
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
Input: s = "abc", t = "ahbgdc"
s: "abc", t: "ahbgdc"
Output: true
Output: true
Solution
The greedy approach is to use two pointers. One pointer for `s` and one for `t`. We iterate through `t` and if we find a character that matches the character at the `s` pointer, we advance the `s` pointer. If the `s` pointer reaches the end of `s`, then `s` is a subsequence of `t`.
Algorithm Steps
- Initialize two pointers, `i` for `s` and `j` for `t`.
- Iterate with the `j` pointer through `t`.
- If `s[i]` matches `t[j]`, increment `i`.
- If `i` equals the length of `s`, it means we have found all characters of `s` in `t` in the correct order.
Is Subsequence
Greedy with Two Pointers
Input: s = "abc", t = "ahbgdc"
Output: false
Ready to start the visualization
s
t