Problem overview
The method numDistinct gets two strings, s and t, and returns how many ways you can delete letters from s so that exactly t is left. The kept letters stay in their order, and two ways are different when they keep different positions of s, even if the letters are the same. The count can have hundreds of digits, so the method returns it modulo 1,000,000,007.
For s = "banana" and t = "ban" the answer is 3. The only b is at position 0, the a can be at position 1 or 3, and the n must come after that a. The kept positions are [0,1,2], [0,1,4] and [0,3,4]. For "llama" and "lama" the answer is 2 (delete either l), and for "cat" and "tac" it is 0, because deleting letters never changes the order of the rest.
Both strings have up to 1,000 letters. The statement asks for O(m · n) time, where m and n are the lengths of s and t.
Approach: count with a table, one letter of s at a time
Trying every set of letters to keep means looking at 2^m subsets, far too many. Counting is better. Let ways[j] be the number of ways to make the first j letters of t using only the letters of s read so far. Before any letter is read, ways[0] is 1, because deleting everything leaves the empty start of t in exactly one way, and every other entry is 0.
Now read s one letter at a time. A letter can only help build the first j letters of t as their last letter, and only when it equals t[j - 1]. Every way to make the first j - 1 letters can then be extended with this letter. These ways join the ones that skip the letter, which are already counted in ways[j]. So when the letter matches, ways[j] grows by ways[j - 1].
The answer is ways[n] after the last letter of s, where n is the length of t. A full table would be m + 1 rows by n + 1 columns. Each row depends only on the one above, so a single row is enough, as long as it is updated in the right order.
Step by step
- Store the length of
tinn. - Create
waysas anint[]of sizen + 1. A new int array starts with every slot at 0. - Set
ways[0] = 1. The empty start ofthas one way: delete every letter. - Loop over the letters of
swithifrom 0 tos.length() - 1. Each pass adds one more letter to the counts. - Loop
jfromndown to 1. The direction matters, as the key step shows. - Check for a match:
t.charAt(j - 1) == s.charAt(i). The comparison is between twocharvalues, so==is correct here. - Add the ways (the key step):
ways[j] = (ways[j] + ways[j - 1]) % 1000000007. Going down,ways[j - 1]still holds its count from before this letter, so the letter ofsis used at most once in each way. Going up,ways[j - 1]would already include the current letter, which could then be used twice. - Return
ways[n].
The table for s = "banana", t = "ban", with entries ways[0] to ways[3] after each letter:
| after | ways |
|---|---|
| start | [1, 0, 0, 0] |
| b | [1, 1, 0, 0] |
| a | [1, 1, 1, 0] |
| n | [1, 1, 1, 1] |
| a | [1, 1, 2, 1] |
| n | [1, 1, 2, 3] |
| a | [1, 1, 3, 3] |
The last entry, 3, is the answer. The second a raises ways[2] to 2 (ba can end at either a), and the second n then adds both of them to ways[3].
The solution in Java
class Solution {
public int numDistinct(String s, String t) {
int n = t.length();
int[] ways = new int[n + 1];
ways[0] = 1;
for (int i = 0; i < s.length(); i++) {
for (int j = n; j >= 1; j--) {
if (t.charAt(j - 1) == s.charAt(i)) {
ways[j] = (ways[j] + ways[j - 1]) % 1000000007;
}
}
}
return ways[n];
}
}
Java details that matter:
- Integer overflow. An
intholds up to 2,147,483,647 and wraps silently past it. Both counts are below 1,000,000,007 after the%, so their sum is below 2,000,000,014, which still fits. That is whyintis enough and nolongis needed. Without the%,s = "a"repeated 1000 times andt = "a"repeated 500 times wraps to the wrong value 888842816; with it the method returns 159835829. - Parentheses around the sum.
%binds tighter than+, soways[j] + ways[j - 1] % 1000000007would reduce only the second term. charAtreturns achar. Comparing two chars with==compares their values, unlike comparing twoStringobjects.
Complexity
Time is O(m · n): each of the m letters of s goes over the n entries of the table. Space is O(n): the table holds n + 1 numbers.
Edge cases and common mistakes
- Looping upward. With
s = "lemon"andt = "mm"there is only onem, so the answer is 0. Going up throughj, the singlemis counted as both letters ofmmand the method returns 1. - Repeated letters.
"aaaa"and"aa"gives 6, the number of ways to choose 2 of the 4 positions. tlonger thans."abc"and"abcd"gives 0:ways[4]can never be reached.- Equal strings.
"a"and"a"gives 1. - Forgetting
ways[0] = 1. Every entry would stay 0 and the answer would always be 0. - Forgetting the modulo. The counts grow like binomial coefficients and overflow
intlong before the strings reach 1,000 letters.
Testing
| s | t | Result |
|---|---|---|
"banana" | "ban" | 3 |
"llama" | "lama" | 2 |
"cat" | "tac" | 0 |
"lemon" | "mm" | 0 |
"aaaa" | "aa" | 6 |
"abc" | "abcd" | 0 |
"a" | "a" | 1 |
1000 times "a" | 500 times "a" | 159835829 |
