Distinct Subsequences
Count the ways to spell one string by picking letters, in order, out of another.
Given two strings sttssssts
Example 1
Output: 3
Explanation: rabbit needs two of the three b's in rabbbit, and there are three ways to choose which two.
Example 2
Output: 5
The Idea
Think of s
Listing the picks works for seven tiles, but a longer s
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 st
The rows, listed under "letters of s read", show how much of st
When the newly read letter is not the last letter of the column's piece of t
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 ssstt
What one cell holds
How does a cell look in code? Call the table dpdp[r][j]tsdp[7][3]
The reasoning about the last g becomes a rule for every cell. The entry dp[r][j]dp[r - 1][j]stdp[r - 1][j - 1]
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
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, wayssways[j - 1]
How large the counts get
Can a count outgrow an intsttintwayslonglong
Java Solution
The method numDistinct
- First, create the array
withways slots, wherem + 1 is the length ofm , and sett to 1: the empty start ofways[0] is formed by picking nothing. The other slots start at 0, like the row (nothing) in the picture.t - Read
one letter at a time with an outer loop over the positions , and keep the current letter ini .c - Inside, a second loop moves
fromj down to 1. Whenm equals the j-th letter ofc , which ist , addt.charAt(j - 1) toways[j - 1] . Those are the picks thatways[j] finishes. On no match,c keeps the count from the row above.ways[j] - After the last letter of
,s holds the number of ways to form all ofways[m] , and the method returns it.t
The maintstts
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:
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"t = "aa"tint
The direction of the inner loop decides the third line. If jmways[1]ways[2]s
Complexity
The work is one pass over the letters of ts
- Time: O(n × m), because each of the n letters of
runs the inner loop over the m letters ofs , with one comparison and at most one addition per step.t - Space: O(m), because the single
array of m + 1ways values stands in for the full table of (n + 1) × (m + 1) cells.long