Start learning free

LESSON 251 OF 314 · DYNAMIC PROGRAMMING

Distinct Subsequences in Java: O(m·n) Time, O(n) Space DP

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

    JAVA · DYNAMIC PROGRAMMING

    Distinct Subsequences in Java, explained

    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

    1. Store the length of t in n.
    2. Create ways as an int[] of size n + 1. A new int array starts with every slot at 0.
    3. Set ways[0] = 1. The empty start of t has one way: delete every letter.
    4. Loop over the letters of s with i from 0 to s.length() - 1. Each pass adds one more letter to the counts.
    5. Loop j from n down to 1. The direction matters, as the key step shows.
    6. Check for a match: t.charAt(j - 1) == s.charAt(i). The comparison is between two char values, so == is correct here.
    7. 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 of s is used at most once in each way. Going up, ways[j - 1] would already include the current letter, which could then be used twice.
    8. Return ways[n].

    The table for s = "banana", t = "ban", with entries ways[0] to ways[3] after each letter:

    afterways
    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 int holds 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 why int is enough and no long is needed. Without the %, s = "a" repeated 1000 times and t = "a" repeated 500 times wraps to the wrong value 888842816; with it the method returns 159835829.
    • Parentheses around the sum. % binds tighter than +, so ways[j] + ways[j - 1] % 1000000007 would reduce only the second term.
    • charAt returns a char. Comparing two chars with == compares their values, unlike comparing two String objects.

    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" and t = "mm" there is only one m, so the answer is 0. Going up through j, the single m is counted as both letters of mm and the method returns 1.
    • Repeated letters. "aaaa" and "aa" gives 6, the number of ways to choose 2 of the 4 positions.
    • t longer than s. "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 int long before the strings reach 1,000 letters.

    Testing

    stResult
    "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
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free