easy Is Subsequence
Problem Statement
Given two strings s and t, return true if the string s is a subsequence of the string t. Otherwise, return false.
A subsequence of a string is a new string that can be formed from the original string by eliminating some (can be zero) of the characters without changing the order of the remaining characters.
Examples
-
Example 1:
- Input:
s = "hello",t = "xyhealoloo" - Expected Output: true
- Justification: By removing "x", "y", "a", "o", and the second "o" from
t,scan be obtained while maintaining the original order.
- Input:
-
Example 2:
- Input:
s = "axc",t = "ahbgdc" - Expected Output: false
- Justification: There is no way to remove characters from
tto achieveswithout altering the sequence of "axc".
- Input:
-
Example 3:
- Input:
s = "abc",t = "aabc" - Expected Output: true
- Justification: By removing the first "a" in
t,sis formed while preserving the character sequence.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Is Subsequence
Problem Statement
Given two strings s and t, return true if the string s is a subsequence of the string t. Otherwise, return false.
A subsequence of a string is a new string that can be formed from the original string by eliminating some (can be zero) of the characters without changing the order of the remaining characters.
Examples
-
Example 1:
- Input:
s = "hello",t = "xyhealoloo" - Expected Output: true
- Justification: By removing "x", "y", "a", "o", and the second "o" from
t,scan be obtained while maintaining the original order.
- Input:
-
Example 2:
- Input:
s = "axc",t = "ahbgdc" - Expected Output: false
- Justification: There is no way to remove characters from
tto achieveswithout altering the sequence of "axc".
- Input:
-
Example 3:
- Input:
s = "abc",t = "aabc" - Expected Output: true
- Justification: By removing the first "a" in
t,sis formed while preserving the character sequence.
- Input:
Solution
To solve this problem, we adopt a two-pointer technique that iteratively compares characters from s and t. One pointer is used to traverse s, and another pointer for t. The idea is to advance both pointers when characters match, indicating that part of the subsequence has been found. When characters do not match, only the pointer for t advances, searching for the next potential matching character.
This method is effective because it linearly scans through both strings simultaneously, ensuring that the relative order of characters in s is maintained in t. By the end of the traversal, if we have successfully navigated through all characters in s, it confirms that s is indeed a subsequence of t.
Step-by-Step Algorithm
-
Initialize Pointers: Start by initializing two pointers,
indexSandindexT, to 0. These pointers will be used to traverse through the stringssandt, respectively. -
Traverse Through
t: Begin a loop that continues as long asindexTis less than the length oftandindexSis less than the length ofs. This loop will go through each character oftto check againsts. -
Check Character Match: Inside the loop, compare the current character of
t(pointed to byindexT) with the current character ofs(pointed to byindexS).- If the characters match, increment
indexSby 1 to move to the next character ins. This step is crucial as it indicates that part of the subsequence has been found.
- If the characters match, increment
-
Move to Next Character in
t: After the check or in case of a mismatch, incrementindexTby 1 to continue scanning throught. -
Check Subsequence Found: After exiting the loop, check if
indexSequals the length ofs. This condition signifies that all characters inshave been found intin the correct order.- If
indexSequals the length ofs, returntrue, indicatingsis a subsequence oft. - If the loop ends and
indexSis not equal to the length ofs, returnfalse, indicatingsis not a subsequence oft.
- If
Algorithm Walkthrough
Let's consider the Input: s = "hello", t = "xyhealoloo"
- Initial Setup:
indexS = 0,indexT = 0.
- Step 1: Begin Loop
indexT = 0,t[0] = 'x',indexS = 0,s[0] = 'h'. They do not match, so onlyindexTis incremented.
- Step 2: Next Iteration
indexT = 1,t[1] = 'y', still no match. IncrementindexT.
- Step 3: Finding 'h'
indexT = 2,t[2] = 'h', matchess[0] = 'h'. Increment bothindexSandindexT.
- Step 4: Finding 'e'
- Continue to
indexT = 3,t[3] = 'e', matchess[1] = 'e'. Increment bothindexSandindexT.
- Continue to
- Step 5: Skipping to 'l'
indexTincrements through 'a', until it finds the first 'l' atindexT = 5.s[2] = 'l'matches, increment both.
- Step 6: Finding Second 'l'
indexT = 6,t[6] = 'o', no match, incrementindexT.indexT = 7,t[7] = 'l', matchess[3] = 'l'. Increment both.
- Step 7: Finding 'o'
indexT = 8,t[8] = 'o', matchess[4] = 'o'. Increment both.
- Step 8: Conclusion
- Now,
indexS = 5, which equals the length ofs. This means every character inshas been found intin order, confirmingsis a subsequence oft.
- Now,
Code
public class Solution {
// Method to check if 's' is a subsequence of 't'
public boolean isSubsequence(String s, String t) {
int indexS = 0, indexT = 0; // Initialize pointers for 's' and 't'
// Traverse 't' to find all chars of 's'
while (indexT < t.length() && indexS < s.length()) {
if (t.charAt(indexT) == s.charAt(indexS)) {
indexS++; // Move to next char in 's' if match found
}
indexT++; // Always move to next char in 't'
}
return indexS == s.length(); // Check if all chars in 's' were found
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(solution.isSubsequence("hello", "xyhealoloo")); // true
// Example 2
System.out.println(solution.isSubsequence("axc", "ahbgdc")); // false
// Example 3
System.out.println(solution.isSubsequence("abc", "aabc")); // true
}
}
Complexity Analysis
Time Complexity
The time complexity of the algorithm is t. This is because, in the worst case, we traverse the entire string t once, comparing each character with characters from s. The traversal and comparisons for each character occur in constant time.
Space Complexity
The space complexity is indexS and indexT) are used, regardless of the input size. This makes the space complexity constant, as it does not scale with the size of the input strings.
🤖 Don't fully get this? Learn it with Claude
Stuck on Is Subsequence? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Is Subsequence** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Is Subsequence** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Is Subsequence**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Is Subsequence**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.