Is Subsequence

Check whether one string can be made from another by deleting characters, without changing the order of the rest.

Given two strings s and t, return true if s is a subsequence of t, and false otherwise. A subsequence of t is what is left after deleting some of its characters, possibly none, without changing the order of the characters that stay.

Example 1
Input: s = "abc", t = "ahbgdc"
Output: true
Explanation: a, b and c appear in t at positions 0, 2 and 5.
Example 2
Input: s = "axc", t = "ahbgdc"
Output: false
Explanation: there is no x in t.
Example 3
Input: s = "axc", t = "ahbgdcx"
Output: false
Explanation: every letter is in t, but x comes after c, not between a and c.
Solution

The Idea

Write the word "ahbgdc" on paper and cross out the h, the g and the d. The letters left over read "abc". Crossing out letters is all that deleting means here, and the letters that stay keep their places. So the question is whether we can cross out letters of t until exactly s is left.

Example 2 fails for a plain reason: t has no x, so no amount of crossing out produces "axc". Example 3 is less obvious. Now "ahbgdcx" has an a, an x and a c, yet the answer is still false. The only c sits at position 5 and the only x at position 6, so after the x there is nothing left to give us the c.

So the order matters, and that raises a question. When we read t from left to right, looking for the letters of s one by one, which copy of a letter should we take if it appears more than once? Look at the picture below.

Example 1: a, b and c of s match t at positions 0, 2 and 5, so the answer is true. Example 3: a matches position 0 and x matches position 6, the last one, so no c is left after x and the answer is false.

In the top half, labelled Example 1, the a of s takes the a at position 0 of t. The search for b skips the h and takes position 2. The search for c skips the g and the d and takes position 5. Every letter of s found a place, so the answer is true.

In the bottom half, labelled Example 3, the a again takes position 0. The search for x has to pass the c at position 5 and finds x only at position 6, the last one. The c of s, shown in red, has nothing left to match, so the answer is false.

Notice that each letter took the first copy it met. That answers the question: taking the earliest copy is always safe, because it leaves as much of t as possible for the letters still to come. A later copy could only leave fewer letters to choose from.

Solution Approach

Turning that idea into code means settling three things: how to keep track of both strings, why taking the earliest match never needs undoing, and when to stop. It also helps to see why trying every way of crossing out is slow, and how to handle many strings s against the same t.

Trying every way of crossing out

Why not build every string that crossing out letters of t can give, and look for s among them? Each letter of t is either kept or crossed out, so a t of n letters gives 2n choices. That is 64 for "ahbgdc", but more than 1030 for a string of 100 letters.

Keeping track of both strings

What do we need to remember while reading t? Only two positions. i points at the letter of s we are looking for now, and j points at the letter of t we are reading. j moves one step on every turn. i moves only when the two letters are equal.

Both positions only ever move forward, each through its own string. Walking two strings with one marker in each like this is a form of the two-pointer technique, where a pointer is simply a position in a string or array.

Why the earliest match is never wrong

Could taking the first copy of a letter ever cost us a match later? Suppose s can be matched using a later copy. Swap that copy for the first copy after the previous match: the letters after it in s still have all the same places of t available, and possibly more. So whenever any matching exists, the earliest-first matching works too, and no choice ever has to be taken back.

When to stop

When is the answer known? If i reaches the end of s, every letter has found a place in order, and the rest of t does not matter. If j reaches the end of t first, some letter of s was never found. In both cases the answer is whether i got to the end of s.

Optional: many strings s against one t

What if t is very long and we must check thousands of strings s against it? Reading all of t again for each one wastes time. Instead, read t once and store, for each letter, the sorted list of positions where it appears. For "ahbgdc", the list for c is just [5].

Then, for each letter of s, look in that letter's list for the first position after the previous match. Because the list is sorted, a binary search finds it by halving the list again and again, without reading every entry.

Java Solution

The method isSubsequence works in these steps:

  1. First, set i to 0. It is the position in s of the next letter to find.
  2. A for loop moves j along t, one letter per turn. It stops at the end of t, or as soon as i reaches s.length(), because then every letter has been found.
  3. Inside the loop, compare s.charAt(i) with t.charAt(j). If they are equal, the letter is found at its earliest place, so i moves on to the next letter of s.
  4. After the loop, return whether i == s.length(), that is, whether every letter of s was found.

The check i < s.length() in the loop condition also keeps s.charAt(i) from reading past the end of s.

The main method runs the three examples, two letters in the wrong order, a repeated letter, an empty s and an empty t.

Java
public class IsSubsequence {

    public static boolean isSubsequence(String s, String t) {
        int i = 0;                            // next character of s to find
        for (int j = 0; j < t.length() && i < s.length(); j++) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;                          // found it; look for the next one
            }
        }
        return i == s.length();
    }

    public static void main(String[] args) {
        System.out.println(isSubsequence("abc", "ahbgdc"));
        System.out.println(isSubsequence("axc", "ahbgdc"));
        System.out.println(isSubsequence("axc", "ahbgdcx"));
        System.out.println(isSubsequence("ba", "abc"));
        System.out.println(isSubsequence("aab", "ab"));
        System.out.println(isSubsequence("aab", "abab"));
        System.out.println(isSubsequence("", "abc"));
        System.out.println(isSubsequence("a", ""));
    }
}

Running it prints:

Output
true
false
false
false
false
true
true
false

The answers true, false, false at the top match the three examples. The fourth line, false, is for "ba" in "abc". Both letters are in "abc", but there the a comes before the b, the opposite of "ba". A check that only asks whether each letter appears somewhere would wrongly say yes.

Lines five and six test a repeated letter. "aab" needs two a's, and "ab" has only one, so the fifth line is false. In "abab" the two a's sit at positions 0 and 2 and a b follows at 3, so the sixth line is true.

The last two lines are the empty cases. An empty s gives true: the loop never runs, and i is already equal to the length, 0. An s of "a" against an empty t gives false, because there is nothing to read.

The original implementation, IsSubsequence.java, is on GitHub.

Complexity

The work is a single left-to-right read of t, with one comparison per letter read.

  • Time: O(n) for a t of n letters, because j visits each letter of t at most once, and the loop may stop earlier, as soon as the last letter of s is found.
  • Space: O(1). The method keeps only the two positions i and j, with no copies of the strings and no lookup tables.