Problem overview
The method numDistinct receives two strings, s and t. It returns how many ways there are to delete letters from s so that exactly t is left. The kept letters stay in their original order, and two ways are different when they keep different positions of s. The count can have hundreds of digits, so the method returns it modulo 1,000,000,007. Both strings have 1 to 1,000 lowercase letters.
For s = "banana" and t = "ban" the answer is 3. Position 0 holds the only b, the a can be the one at position 1 or the one at position 3, and the n must come after that a. The kept positions are [0, 1, 2], [0, 1, 4] or [0, 3, 4]. For "llama" and "lama" the answer is 2, because either l can be deleted. For "cat" and "tac" it is 0: deleting letters never changes the order of the rest.
The statement asks for O(m · n) time, where m and n are the lengths of s and t.
Approach: count how many ways each prefix of t can be made
Trying every set of letters to keep is far too slow: a string of 1,000 letters has more subsets than can ever be counted one by one. Counting with a table avoids that.
Let ways[j] be the number of ways to make the first j letters of t from the letters of s read so far. Before any letter of s is read, ways[0] is 1, because the empty start of t can be made in exactly one way: delete everything. Every other entry is 0. The answer is ways[n] after the last letter of s, where n is the length of t.
Now read s one letter at a time. Take the letter s[i] and an entry j. If t[j - 1] is a different letter, s[i] can't help to make the first j letters, and ways[j] stays as it is. If t[j - 1] equals s[i], there are two kinds of ways: the ones that don't use this letter, which are already counted in ways[j], and the ones that use it as the last kept letter. Those are exactly the ways to make the first j - 1 letters before this letter, followed by it. So ways[j] grows by ways[j - 1].
This is a two-dimensional table (letters of s by letters of t) in which each row only reads the row above, so one row is enough: O(n) extra space.
Step by step
- Store the length.
n = len(t). - Create the table.
ways = [0] * (n + 1)has one entry for each prefix length from 0 ton. - Set
ways[0] = 1, the one way to make the empty prefix. - Read
sletter by letter withfor i in range(len(s)). - Go through the entries from
ndown to 1:for j in range(n, 0, -1). With a step of -1,rangecounts down and stops before 0. - Compare the letters. If
t[j - 1] == s[i], the letter can end a way to make the firstjletters. - Add the ways.
ways[j] = (ways[j] + ways[j - 1]) % 1000000007. Taking the remainder at every addition keeps the numbers small. - Return
ways[n].
The direction of step 5 is the key. Going down, when entry j is updated, ways[j - 1] has not been touched for this letter yet, so it holds its count from before the letter. Going up, ways[j - 1] would already include this letter, and a single letter could be used twice in the same way.
The solution in Python
class Solution:
def numDistinct(self, s: str, t: str) -> int:
n = len(t)
ways = [0] * (n + 1)
ways[0] = 1
for i in range(len(s)):
for j in range(n, 0, -1):
if t[j - 1] == s[i]:
ways[j] = (ways[j] + ways[j - 1]) % 1000000007
return ways[n]
Python details worth noting:
[0] * (n + 1)builds a list ofn + 1zeros. Integers are immutable, so repeating a zero this way is safe. Repeating a list of lists with*is the version that shares rows.range(n, 0, -1)yieldsn, n - 1, ..., 1. The end value 0 is excluded.%with positive numbers. The sum of two numbers below the modulus is below twice the modulus, and the remainder brings it back into range. Python integers never overflow, so the modulus is there because the lesson asks for it, not to protect the arithmetic. Without it the counts would be correct but could have hundreds of digits.- Indexing a string with
t[j - 1]gives a one-letter string, and==compares letters by value.
Tracing "banana" and "ban"
These are the values of ways after each letter of s, with the starting list first:
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 is the answer, 3. The first a makes "ba" in one way, and the second a makes it in a second way, so ways[2] becomes 2. The second n can end both of those, so it adds 2 to the 1 that ways[3] already had, giving 3.
More runs
numDistinct("llama", "lama") = 2
numDistinct("cat", "tac") = 0
numDistinct("a", "aa") = 0
numDistinct("aaa", "aa") = 3
Complexity
Time: O(m · n). Each of the m letters of s goes over n entries, and each step is a comparison and possibly an addition. For two strings of 1,000 letters that is about a million steps.
Space: O(n). The table holds n + 1 numbers, however long s is.
Edge cases and common mistakes
tlonger thans.numDistinct("a", "aa")is 0, because there are not enough letters to keep.- Repeated letters.
numDistinct("aaa", "aa")is 3, one for each pair of positions. The same letter value at different positions counts as different ways. - Looping upward. Going from 1 up to
nlets one letter ofsserve several positions oft. Fors = "lemon"andt = "mm", the singlemwould make"mm"and the method would return 1 instead of 0. The same upward loop returns 6 instead of 3 for"aaa"and"aa". - Forgetting
ways[0] = 1. Every entry would stay 0, since each count is built from the one before it. - Skipping the modulus. In Python the numbers are still correct, but the answer would not match the tests for large inputs. For 1,000 letters
ainsand 500 int, the true count has 300 digits, and the lesson's answer is 159835829. - Counting different strings. The task counts position choices, not different resulting strings. Here the result is always
t, so only the choices of positions differ.
