Easy dsa two-pointers

Is Subsequence

The 30 second answer

I walk the longer string once and advance a pointer in the shorter string whenever the characters match. If that pointer reaches the end, every character of s appeared in order inside t. One pass over t and constant extra space.

Could you say this in an interview?

Problem Return true if string s is a subsequence of string t: the characters of s appear in t in the same order, but not necessarily contiguously. Original: LeetCode 392: Is Subsequence.

Understanding the prompt Order matters, adjacency does not. An empty s is a subsequence of every t, including an empty t. If s is longer than t the answer is false.

Pattern recognition Two pointers moving forward through two sequences, advancing the s-pointer only on a match. This is a read/read pair, not an in-place write.

Brute force Generate all subsequences of t and test membership: exponential. A DP table of LCS length is O(|s| · |t|), which is more than you need for a yes/no.

Optimal i walks s, j walks t. Whenever s.charAt(i) == t.charAt(j), increment i. If i reaches s.length(), you have matched every character.

Alternatives If you must answer many s queries against one fixed t, precompute for each position in t the next occurrence of every character, then jump in O(|s|) per query after O(|t| · Σ) preprocessing.

Java solution

public class IsSubsequence {
    static boolean isSubsequence(String s, String t) {
        int i = 0;
        for (int j = 0; j < t.length() && i < s.length(); j++) {
            if (s.charAt(i) == t.charAt(j)) i++;
        }
        return i == s.length();
    }

    public static void main(String[] args) {
        System.out.println(isSubsequence("abc", "ahbgdc")); // true
        System.out.println(isSubsequence("axc", "ahbgdc")); // false
        System.out.println(isSubsequence("", "ahbgdc"));    // true
        System.out.println(isSubsequence("abc", ""));       // false
    }
}

Complexity O(|t|) time, O(1) extra space.

Edge cases

  • Empty s returns true.
  • Empty t and non-empty s returns false.
  • Repeated letters: " abc" in " ahbgdc" is true; " axc" is false because 'x' never appears.

Follow-ups

  • Longest Common Subsequence is the DP generalisation when you want the length, not a yes/no.
  • Many queries on one t: precompute next-occurrence jumps.

Tests (" abc", " ahbgdc") returns true. (" axc", " ahbgdc") returns false. ("", " ahbgdc") returns true. (" abc", "") returns false.

How to say it in the interview "I scan t once and advance a pointer in s whenever the characters match. If that pointer reaches the end of s, s is a subsequence. Linear in t, constant space."

Sources (1)
  1. LeetCode 392: Is Subsequenceleetcode.com