LeetCode #115 Hard

Distinct Subsequences

Distinct Subsequences is LeetCode 115 (Hard). Given strings s and t, count the subsequences of s that equal t. A subsequence keeps some characters of s in their original order, and two subsequences count as different when they use different positions of s, even if they spell the same thing.

  • Both strings have up to 1000 letters, so about 10⁶ steps is fine.
  • The final answer fits in a 32-bit integer, but the counts along the way may not.
Constraints
  • 1 <= s.length, t.length <= 1000
  • s and t consist of English letters.
stringdynamic-programmingsubsequence
Open on LeetCode ↗
02

Intuition

Let ways[j] be the number of ways to spell the first j letters of t using the part of s read so far. Before anything is read, ways[0] = 1 (spell nothing by choosing nothing) and every other entry is 0.

When the next letter of s equals t[j − 1], every way to spell the first j − 1 letters can be finished with this letter, so ways[j] grows by ways[j − 1]. The old ways, which skip this letter, still count as well, which is why it is an addition and not a replacement.

Read s once, updating ways after each letter, and ways[len(t)] is the answer.

How to spot this pattern

Counting the ways to pick positions from one sequence so they spell another is a two-string DP whose state is how much of the target is spelled so far. The choice to use or skip each letter turns into an addition.

03

Approach

Try it first

Before reading on, list by hand every way to pick bag out of babgbag, writing each one as the positions it uses. Then look at how the count for ba feeds the count for bag. Aim for O(|s| · |t|) time and O(|t|) space.

1

Start with one way to spell nothing

Create ways with len(t) + 1 entries: ways[0] = 1 and the rest 0. The empty prefix of t is spelled exactly one way, by choosing nothing, and longer prefixes have no ways yet because no letter of s has been read.

2

Read s one letter at a time

For each letter ch of s, visit j from len(t) down to 1 and, wherever t[j - 1] == ch, add ways[j - 1] to ways[j]. Going downwards means ways[j - 1] still holds its count from before this letter.

3

Why each choice is counted exactly once

A set of positions that spells the first j letters of t is added at one moment only: when its last letter is read, through the count for its first j − 1 letters. Two different sets differ in some position, so they are added along different paths and never merge.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numDistinct(self, s, t):
▶3 n = len(t)
▶4 ways = [1] + [0] * n
▶5 for ch in s:
▶6 for j in range(n, 0, -1):
▶7 if ch == t[j - 1]:
▶8 ways[j] += ways[j - 1]
▶9 return ways[n]
sbabgbagways to spell each prefix of t1empty0b0ba0bag+=one way to spell nothing; no way to spell more yet
sbabgbag
tbag
Before any letter of s is read, the empty prefix of t can be spelled exactly one way, by choosing nothing. Every longer prefix needs letters, so its count starts at 0.
sbabgbagways to spell each prefix of t1empty1b0ba0bag0before+1ways for empty=1ways for bletter 1 is b → ways for b grow by 1
letter of s1 (b)
prefixb
ways1
This b can be the last letter of b. The one way to spell the empty prefix so far can be finished with it, so the total becomes 1.
sbabgbagways to spell each prefix of t1empty1b1ba0bag0before+1ways for b=1ways for baletter 2 is a → ways for ba grow by 1
letter of s2 (a)
prefixba
ways1
This a can be the last letter of ba. The one way to spell b so far can be finished with it, so the total becomes 1.
sbabgbagways to spell each prefix of t1empty2b1ba0bag1before+1ways for empty=2ways for bletter 3 is b → ways for b grow by 1
letter of s3 (b)
prefixb
ways2
This b can be the last letter of b. The one way to spell the empty prefix so far can be finished with it, and the 1 way that skips it still counts, so the total becomes 2.
sbabgbagways to spell each prefix of t1empty2b1ba1bag0before+1ways for ba=1ways for bagletter 4 is g → ways for bag grow by 1
letter of s4 (g)
prefixbag
ways1
This g can be the last letter of bag. The one way to spell ba so far can be finished with it, so the total becomes 1.
sbabgbagways to spell each prefix of t1empty3b1ba1bag2before+1ways for empty=3ways for bletter 5 is b → ways for b grow by 1
letter of s5 (b)
prefixb
ways3
This b can be the last letter of b. The one way to spell the empty prefix so far can be finished with it, and the 2 ways that skip it still count, so the total becomes 3.
sbabgbagways to spell each prefix of t1empty3b4ba1bag1before+3ways for b=4ways for baletter 6 is a → ways for ba grow by 3
letter of s6 (a)
prefixba
ways4
This a can be the last letter of ba. Each of the 3 ways to spell b so far can be finished with it, and the 1 way that skips it still counts, so the total becomes 4.
sbabgbagways to spell each prefix of t1empty3b4ba5bag1before+4ways for ba=5ways for bagletter 7 is g → ways for bag grow by 4
letter of s7 (g)
prefixbag
ways5
This g can be the last letter of bag. Each of the 4 ways to spell ba so far can be finished with it, and the 1 way that skips it still counts, so the total becomes 5.
sbabgbagways to spell each prefix of t1empty3b4ba5bag+=answer: 5
answer5
All of s has been read. The last count is the number of ways to spell all of bag: 5. Each set of positions was added exactly once, at the moment its last letter was read.
05

Common pitfalls

Updating the row left to right

✗ Wrong
for j in range(1, n + 1):
✓ Right
for j in range(n, 0, -1):

Then ways[j - 1] may already include the current letter, so one letter of s fills two positions of t. On s = "a", t = "aa" the single a first sets ways[1] = 1 and then reuses itself for ways[2], returning 1 instead of 0.

Signed counters in C++

✗ Wrong
vector<long long> ways(n + 1, 0);
✓ Right
vector<unsigned long long> ways(n + 1, 0);

Middle entries can dwarf the answer. With s = 1000 copies of a and t = 500 copies of a then b, the answer is 0 but ways[500] passes 10²⁹⁹, and signed overflow is undefined behaviour, which the online judge reports as a runtime error. Unsigned numbers wrap around modulo 2⁶⁴ instead, and since every update is an addition, the wrapped final value still equals the true answer when that answer is below 2³¹. Java's long wraps the same way, so it is safe as written.

06

Edge cases

t longer than s, e.g. s = "ab", t = "abc"

ways[j] can only become non-zero after j letters of s have matched in order, and s has too few letters, so the answer stays 0.

07

Complexity

Time
O(|s| · |t|)
Space
O(|t|)
Each letter of s scans all of t once. The single row of len(t) + 1 counts replaces the full table, because each row of that table only reads the row above it.
08

Distinct Subsequences FAQ

What does the full two-dimensional table look like?

dp[i][j] is the number of ways to spell the first j letters of t from the first i letters of s, with dp[i][0] = 1. Then dp[i][j] = dp[i − 1][j], plus dp[i − 1][j − 1] when s[i − 1] == t[j − 1]. The one-row version is this table with each row written over the one above it.

How does the recursive version work?

count(i, j) is the number of ways to spell t[j:] from s[i:]. It returns 1 when j == len(t) and 0 when s runs out first. Otherwise it is count(i + 1, j), plus count(i + 1, j + 1) when the letters match. With memoisation it is also O(|s| · |t|) time, but its cache needs O(|s| · |t|) memory.