Distinct Subsequences

Count the ways to spell one string by picking letters, in order, out of another.

Given two strings s and t, count the ways to spell t by picking letters out of s. A pick keeps some letters of s in their original order and leaves the rest out, and the letters it keeps are called a subsequence of s. Return how many subsequences of s spell exactly t. Two picks count as different when they use different positions of s, even though they spell the same word.

Example 1
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation: rabbit needs two of the three b's in rabbbit, and there are three ways to choose which two.
Example 2
Input: s = "babgbag", t = "bag"
Output: 5
Solution

The Idea

Think of s in Example 2 as a row of letter tiles, numbered 1 to 7: b, a, b, g, b, a, g. You want to spell bag by taking tiles from left to right, without moving any. The b can be tile 1, 3 or 5, the a tile 2 or 6, and the g tile 4 or 7, as long as each tile comes after the one before it. That gives five picks: 1-2-4, 1-2-7, 1-6-7, 3-6-7 and 5-6-7.

Listing the picks works for seven tiles, but a longer s has far more of them. Can we count the picks without listing them? Look at the last tile, the g in position 7. Every pick either uses it or leaves it out.

The picks that leave it out spell bag from the first six tiles, babgba, and there is 1 of them: 1-2-4. The picks that use it need their b and a from those same six tiles, so they are the ways to spell ba from babgba, followed by the last g. There are 4 of those: 1-2, 1-6, 3-6 and 5-6. Together that makes 1 + 4 = 5.

Both smaller counts answer the same kind of question as the first one: in how many ways does the start of s spell the start of t? So it pays to write every such count into a table, like the one in the picture below.

The table of counts for s = babgbag and t = bag. Rows are the letters of s read, from nothing to babgbag. Columns are the start of t to form: empty, b, ba, bag. The last cell, 5, is the 1 in row babgba, column bag, plus the 4 in row babgba, column ba.

The rows, listed under "letters of s read", show how much of s has been read, from (nothing) down to all of babgbag. Each column, under "start of t to form", is a piece of t, from the empty string "" to all of "bag". In row babgba, the column "ba" holds 4 and the column "bag" holds 1. The bottom-right cell adds the two: 1 way to form "bag" that skips the last g, plus 4 ways to form "ba" that the last g can finish, which is 5.

When the newly read letter is not the last letter of the column's piece of t, it cannot finish anything, and the cell copies the count above it. Row babgb, column "ba" holds 1, the same as row babg, because the new b is not an a. Answering the question for all of babgbag from answers for shorter pieces of it, each written down once in this table, is called dynamic programming.

Solution Approach

Turning the table into code means settling five things: why listing every pick is slow, what one cell holds, where the table starts, how to keep one row, and how big the counts get.

Listing every pick

Why not try every pick of letters from s? Each letter is either kept or left out, so a string s of n letters has 2n picks. For babgbag that is 128, but 40 letters give about 1.1 × 1012. The table instead has one cell for each pair of a start of s and a start of t, which is (n + 1) × (m + 1) cells when t has m letters.

What one cell holds

How does a cell look in code? Call the table dp. The entry dp[r][j] is the number of ways to form the first j letters of t from the first r letters of s. Counting rows from (nothing) as 0 and columns from "" as 0, the last cell in the picture is dp[7][3], which is 5.

The reasoning about the last g becomes a rule for every cell. The entry dp[r][j] starts as dp[r - 1][j], the picks that skip the r-th letter of s. When that letter equals the j-th letter of t, add dp[r - 1][j - 1], the picks it can finish.

Where the table starts

What goes in the first row and column? Column "" holds 1 in every row, because the empty string is formed in one way, by picking nothing. Row (nothing) holds 0 in every other column, because with nothing read there are no letters to spell a piece of t that is not empty.

Keeping one row

Does the code need all eight rows of the table? Each row is built from the row above it alone, so one array, ways, can hold the current row and be updated in place as each letter of s is read. The order of the updates matters, though. Slot j needs ways[j - 1] as it was in the row above, before the new letter changed it. Going from the last slot down to the first keeps that true: when slot j is updated, slot j - 1 has not been touched yet.

How large the counts get

Can a count outgrow an int? Take s as 40 a's and t as 20 a's. Any 20 of the 40 positions spell t, and there are 137,846,528,820 such choices, far past the 2,147,483,647 that an int can store. So ways holds long values, and the method returns a long.

Java Solution

The method numDistinct works in these steps:

  1. First, create the array ways with m + 1 slots, where m is the length of t, and set ways[0] to 1: the empty start of t is formed by picking nothing. The other slots start at 0, like the row (nothing) in the picture.
  2. Read s one letter at a time with an outer loop over the position i, and keep the current letter in c.
  3. Inside, a second loop moves j from m down to 1. When c equals the j-th letter of t, which is t.charAt(j - 1), add ways[j - 1] to ways[j]. Those are the picks that c finishes. On no match, ways[j] keeps the count from the row above.
  4. After the last letter of s, ways[m] holds the number of ways to form all of t, and the method returns it.

The main method runs both examples, a t longer than s, an empty t, a t whose letters appear in s only in the wrong order, and the 40 a's from above.

Java
public class DistinctSubsequences {

    public static long numDistinct(String s, String t) {
        int m = t.length();
        long[] ways = new long[m + 1]; // ways[j]: ways to form the first j letters of t
        ways[0] = 1;                   // the empty start of t is formed by picking nothing
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            for (int j = m; j >= 1; j--) { // right to left, so c is used once per pick
                if (c == t.charAt(j - 1)) {
                    ways[j] += ways[j - 1];
                }
            }
        }
        return ways[m];
    }

    public static void main(String[] args) {
        System.out.println(numDistinct("rabbbit", "rabbit"));
        System.out.println(numDistinct("babgbag", "bag"));
        System.out.println(numDistinct("a", "aa"));
        System.out.println(numDistinct("abc", ""));
        System.out.println(numDistinct("abc", "ca"));
        System.out.println(numDistinct("a".repeat(40), "a".repeat(20)));
    }
}

Running it prints:

Output
3
5
0
1
0
137846528820

The 3 on top counts the three ways to choose two b's out of rabbbit, and the 5 below it counts the five picks from 1-2-4 to 5-6-7. Look at the third line: s = "a" and t = "aa" give 0, since one letter cannot fill two places. The 1 on the fourth line is the empty t, formed once by picking nothing. The fifth line is 0 because "abc" has a c and an a, but the a comes first, and a pick may not reorder letters. The last line is the 40 a's count in full; cast to an int, it would turn into 407575348.

The direction of the inner loop decides the third line. If j ran from 1 up to m instead, the single a would first raise ways[1] to 1 and then, in the same pass, add that new 1 to ways[2], using one a twice. That version returns 1 for "a" and "aa", and 6 instead of 3 for rabbbit. For babgbag and bag it still returns 5, because bag has no repeated letter for one letter of s to fill twice.

Complexity

The work is one pass over the letters of t for every letter of s.

  • Time: O(n × m), because each of the n letters of s runs the inner loop over the m letters of t, with one comparison and at most one addition per step.
  • Space: O(m), because the single ways array of m + 1 long values stands in for the full table of (n + 1) × (m + 1) cells.

Longest Common Subsequence fills the same kind of table, with one string along the rows and the other along the columns.