0:00 / 0:00

Count the ways to pick letters of s, in order, that spell t: each letter is skipped or used, and a table adds up both choices.

▼

The problem

LeetCode 115 (Hard). Given strings s and t, return the number of distinct subsequences of s that equal t (the number of ways to pick positions of s, in order, that spell t).

Examples (LeetCode's): s = "rabbbit", t = "rabbit" → 3 (drop any one of the three b's: positions 0 1 2 3 5 6, 0 1 2 4 5 6 and 0 1 3 4 5 6) and s = "babgbag", t = "bag" → 5.

TRY IT ON LEETCODE ▶

The solution

def num_distinct(s, t):
    dp = [1] + [0] * len(t)
    for ch in s:
        for j in range(len(t), 0, -1):
            if ch == t[j - 1]:
                dp[j] += dp[j - 1]
    return dp[-1]

Transcript

Distinct Subsequences. You get two strings, s and t. Count the ways to pick letters from s, keeping their order, that spell t. Each way uses different positions.

Take rabbit with an extra b, and plain rabbit, needing two. Drop any one of the three b's: that's three ways. And babgbag holds bag five ways.

The slow way tries every subsequence of s and counts the matches. Each letter is in or out, so seven letters give two to the seventh: one hundred twenty-eight tries, for just three matches. Twenty letters would mean over a million.

The key idea: walk through s, and at each letter, skip it or use it. Let dp of i and j count the ways the first i letters of s spell the first j of t.

Skipping a letter keeps the count from the left. If the letters match, using it adds the count up and to the left. And an empty t has exactly one way. At the second a of babgbag: one from the left, plus three from the diagonal, makes four.

In code, one row is enough. Start it with a one for the empty prefix, then zeros. For each letter of s, sweep t from right to left, and where the letters match, add in the count just before it. Return the last cell.

On babgbag, the first b starts one way to spell b. The second b makes two. The first g completes one bag. The third b makes three. The next a joins all three b's, so b a grows to four. The last g adds those four to the one bag: five.

Why right to left? Sweep the other way with t equals b b, and a single b counts twice: it bumps one cell, then reads its own new value. Right to left only reads the old row. So it's s times t steps of constant work, and one row of space.

Skip it or use it, add the ways, and sweep from the right. That's Distinct Subsequences.