Is Subsequence
Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence is a sequence that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. For example, "ace" is a subsequence of "abcde".
A greedy two-pointer approach works efficiently: iterate through t with pointer j, and for each character in s with pointer i, move j forward until a match is found. If all characters of s are matched, return true. Otherwise, return false. This runs in O(|t|) time with O(1) space.
While simple two pointers suffices, this problem can also be solved with DP: a 2D table dp[i][j] indicates whether s[0..i-1] is a subsequence of t[0..j-1]. The recurrence is dp[i][j] = dp[i][j-1] OR (dp[i-1][j-1] AND s[i-1]==t[j-1]). The two-pointer approach is preferred for a single query.
Edge cases include empty s (always true, since empty string is a subsequence of any string), empty t with non-empty s (false), and exact matches (s equals t).
The two-pointer approach for subsequence checking works in O(n) time because each character in t is examined at most once. This greedy matching strategy works because matching earlier is always at least as good as matching later for future characters.
Example Input & Output
abc is a subsequence of ahbgdc.
Single character match.
Empty string is always a subsequence.
axc is not a subsequence.
Non-empty s cannot be subsequence of empty t.
Algorithm Flow

Solution Approach
Two pointers: iterate through t, matching characters from s. If all s matched, return true.
Time O(|t|), Space O(1).
Best Answers
class Solution {
public boolean solution(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) i++;
j++;
}
return i == s.length();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
