Distinct Subsequences

Pattern: Strings DP

hard

ways[i][j] counts how many ways t's first j characters appear as a subsequence of s's first i. If s[i-1] == t[j-1], use it (ways[i-1][j-1]) or not (ways[i-1][j]); otherwise only not.

The problem

Return how many distinct position sets of s spell out t as a subsequence.

Think first

  • What is ways[i][0]?
  • If the characters match, what are the two choices?
  • And if they do not?

Hints

    Brute force, and why it fails

    Try every subsequence of s: 2ⁿ.

    The key insight

    Each s character is either used for the current t character or not, so the counts add.

    Dry run

    s 'rabbbit', t 'rabbit'. The three b's can be paired with t's two b's in 3 ways.

    Step 1 of 2

    The plan

    ways[i][0] = 1
    ways[i][j] = ways[i-1][j] + (ways[i-1][j-1] if s[i-1] == t[j-1] else 0)
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    One row, updated right to left.

    Edge cases

    • t longer than s: 0.
    • t empty: 1.
    • Large counts.
    I've built my logic, show the code

    Java

    class Solution {
        public int numDistinct(String s, String t) {
            int n = t.length();
            long[] ways = new long[n + 1];          // ways[j]: ways to form t's first j characters from the part of s read so far
            ways[0] = 1;
            for (char c : s.toCharArray())
                for (int j = n; j >= 1; j--)        // downwards: each character of s is used at most once per subsequence
                    if (t.charAt(j - 1) == c) ways[j] += ways[j - 1];
            return (int) ways[n];
        }
    }

    C++

    class Solution {
    public:
        int numDistinct(string s, string t) {
            int n = static_cast<int>(t.size());
            vector<unsigned long long> ways(n + 1, 0);   // ways to form t's first j characters from the part of s read so far
            ways[0] = 1;
            for (char c : s)
                for (int j = n; j >= 1; j--)        // downwards: each character of s is used at most once per subsequence
                    if (t[j - 1] == c) ways[j] += ways[j - 1];
            return static_cast<int>(ways[n]);
        }
    };

    Python

    class Solution:
        def numDistinct(self, s: str, t: str) -> int:
            ways = [1] + [0] * len(t)               # ways[j]: ways to form t's first j characters from s so far
            for c in s:
                for j in range(len(t), 0, -1):      # downwards: each character of s is used at most once per subsequence
                    if t[j - 1] == c:
                        ways[j] += ways[j - 1]
            return ways[-1]

    Common mistakes

    • Updating the row left to right.
    • Setting ways[0][0] = 0.

    Similar problems