CMD Guide
HomeDSACompany Practice

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

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Is Subsequence easy

0. Why / judgment (K3)

Family: Two pointers · subsequence match

s is subsequence of t iff we can match s's chars in order by scanning t once. Two pointers i on s, j on t; advance i on match. Success i==|s|. This is NOT substring (contiguity) and NOT regex.

1. Pattern + recognition + when-NOT (K12)

Pattern / template: i=0; for c in t: if i<|s| and s[i]==c: i+=1; return i==|s|. Recognition: order-preserving delete-only from t to get s.

When-NOT: Not LCS length (unless asking length). Not sliding window for anagram. If many s queries on fixed t → preprocess positions / binary search next index. If must be substring → two pointers with reset or KMP.

2. Complexity derivation (K11)

O(|t|) time, O(1) space single query.

3. Edge hand-run (K13)

s="", t=anything → true.
s="abc", t="ahbgdc" → true.
s="axc", t="ahbgdc" → false.
s longer than t → false fast.

4. Interviewer follow-ups & drills

Q1. Substring vs subsequence?
Model answer: Substring contiguous; subsequence not.

Q2. DP table?
Model answer: Overkill O(|s||t|) for decision only.

Q3. Follow-up many s?
Model answer: Index lists per char + binary search.

✅ 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, s can be obtained while maintaining the original order.
  • Example 2:

    • Input: s = "axc", t = "ahbgdc"
    • Expected Output: false
    • Justification: There is no way to remove characters from t to achieve s without altering the sequence of "axc".
  • Example 3:

    • Input: s = "abc", t = "aabc"
    • Expected Output: true
    • Justification: By removing the first "a" in t, s is formed while preserving the character sequence.

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

  1. Initialize Pointers: Start by initializing two pointers, indexS and indexT, to 0. These pointers will be used to traverse through the strings s and t, respectively.

  2. Traverse Through t: Begin a loop that continues as long as indexT is less than the length of t and indexS is less than the length of s. This loop will go through each character of t to check against s.

  3. Check Character Match: Inside the loop, compare the current character of t (pointed to by indexT) with the current character of s (pointed to by indexS).

    • If the characters match, increment indexS by 1 to move to the next character in s. This step is crucial as it indicates that part of the subsequence has been found.
  4. Move to Next Character in t: After the check or in case of a mismatch, increment indexT by 1 to continue scanning through t.

  5. Check Subsequence Found: After exiting the loop, check if indexS equals the length of s. This condition signifies that all characters in s have been found in t in the correct order.

    • If indexS equals the length of s, return true, indicating s is a subsequence of t.
    • If the loop ends and indexS is not equal to the length of s, return false, indicating s is not a subsequence of t.

Algorithm Walkthrough

Let's consider the Input: s = "hello", t = "xyhealoloo"

  • Initial Setup: indexS = 0, indexT = 0.
  1. Step 1: Begin Loop
    • indexT = 0, t[0] = 'x', indexS = 0, s[0] = 'h'. They do not match, so only indexT is incremented.
  2. Step 2: Next Iteration
    • indexT = 1, t[1] = 'y', still no match. Increment indexT.
  3. Step 3: Finding 'h'
    • indexT = 2, t[2] = 'h', matches s[0] = 'h'. Increment both indexS and indexT.
  4. Step 4: Finding 'e'
    • Continue to indexT = 3, t[3] = 'e', matches s[1] = 'e'. Increment both indexS and indexT.
  5. Step 5: Skipping to 'l'
    • indexT increments through 'a', until it finds the first 'l' at indexT = 5. s[2] = 'l' matches, increment both.
  6. Step 6: Finding Second 'l'
    • indexT = 6, t[6] = 'o', no match, increment indexT.
    • indexT = 7, t[7] = 'l', matches s[3] = 'l'. Increment both.
  7. Step 7: Finding 'o'
    • indexT = 8, t[8] = 'o', matches s[4] = 'o'. Increment both.
  8. Step 8: Conclusion
    • Now, indexS = 5, which equals the length of s. This means every character in s has been found in t in order, confirming s is a subsequence of t.
Image
Image

Code

java
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 , where (n) is the length of string 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 . Only a fixed number of variables (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.

🎯 STRICT STANDOUT — Solution Is Subsequence

0. Why / judgment (K3)

Family: Two pointers subsequence

Greedy earliest match is optimal for existence: delaying a match never helps later constraints for pure existence (can prove by exchange).

1. Pattern + recognition + when-NOT (K12)

Pattern / template: Single scan t; pointer into s.

When-NOT: Don't sort (destroys order).

2. Complexity derivation (K11)

Θ(|t|)/Θ(1).

3. Edge hand-run (K13)

Hand-run s="ace", t="abcde": match a,c,e → true.
s="aec": after a, e matches e before c fails order → false.

4. Interviewer follow-ups & drills

Q1. Why earliest match OK?
Model answer: Any solution matching later can rematch earlier positions.

Q2. Unicode?
Model answer: Iterate code points consistently.

Q3. Hostile empty s?
Model answer: true immediately.

🧩 Pattern · Arrays

Recognize it: Scan once tracking what you need (running max/sum), or precompute a prefix-sum / hash → turn O(n²) into O(n).

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes