Start learning free

LESSON 535 OF 673 · DYNAMIC PROGRAMMING

Distinct Subsequences in Python: O(m·n) Time, 1D Dynamic Programming

Practice O(m · n) Read the full explanation

You get a string s and a string t.

Return how many ways you can delete letters from s so that t is left.

The letters you keep stay in their order. Two ways are different when they keep different positions of s.

The count can have hundreds of digits, so return it modulo 1,000,000,007.

 

Example 1:

Input: s = "banana", t = "ban"
Output: 3
Explanation: Position 0 holds the only b.
The a can be the one at 1 or the one at 3.
The n must come after that a.
So the kept positions are [0,1,2], [0,1,4] or [0,3,4].

Example 2:

Input: s = "llama", t = "lama"
Output: 2
Explanation: Delete the first l or the second l.
Either way, lama is left.

Example 3:

Input: s = "cat", t = "tac"
Output: 0
Explanation: s has the same letters in another order.
Deleting letters never changes the order of the rest.

 

Constraints:

  • s has 1 to 1,000 letters.
  • t has 1 to 1,000 letters.
  • All letters are lowercase English letters.

Note:

Your solution should run in O(m · n) time. Here m and n are the lengths of s and t.



Trying every set of letters to keep is far too slow. Count with a table instead. 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. At the start, ways[0] is 1: deleting everything leaves the empty start of t. Every other entry starts at 0. Here n is the length of t, and the answer is ways[n] after the last letter of s.

Read s one letter at a time. When the letter equals t[j - 1], it can end any way of making the first j - 1 letters. So ways[j] grows by ways[j - 1].
Go over j from n down to 1. Then ways[j - 1] still holds its count from before this letter, and no letter of s is used twice in one way. Going up would let the one m of "lemon" make "mm".

Each of the m letters of s goes over the n entries: O(m · n) time. The table holds n + 1 numbers: O(n) extra space.
STEP 1 OF 8
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Distinct Subsequences in Python, explained

    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

    1. Store the length. n = len(t).
    2. Create the table. ways = [0] * (n + 1) has one entry for each prefix length from 0 to n.
    3. Set ways[0] = 1, the one way to make the empty prefix.
    4. Read s letter by letter with for i in range(len(s)).
    5. Go through the entries from n down to 1: for j in range(n, 0, -1). With a step of -1, range counts down and stops before 0.
    6. Compare the letters. If t[j - 1] == s[i], the letter can end a way to make the first j letters.
    7. Add the ways. ways[j] = (ways[j] + ways[j - 1]) % 1000000007. Taking the remainder at every addition keeps the numbers small.
    8. 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 of n + 1 zeros. 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) yields n, 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

    • t longer than s. 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 n lets one letter of s serve several positions of t. For s = "lemon" and t = "mm", the single m would 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 a in s and 500 in t, 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.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free