DSA Factory
Free Dynamic programming lessonsDynamic programming · Stage 4 · Two strings · Step 4

Counting every way, not finding one

A match now offers a choice — use this letter or skip it — and both ways of counting add together. About 13 minutes.

How many ways can you spell it?

Take the word "rabbbit", with three b's, and ask: in how many different ways can you cross out letters to leave "rabbit"? You have to pick two of the three b's, so there are 3 ways.

Walk through the long word one letter at a time. Every letter can always be skipped: the ways that don't use it are still valid. When it matches the next letter you need, it can also be used, which opens up more ways.

Skipping is always allowed: those ways always count.

A match adds, it doesn't choose

Here's the difference from earlier steps. When a letter matches, you don't choose between using it and skipping it. Both kinds of spelling really exist, so you add them together: the ways that skip this letter, plus the ways that use it as the match.

In the grid, "skip" is the box above and "use" is the box diagonally up-left. With three b's to choose two from, the count grows 1, 2, 3.

Skip: the box above, always.
Use it: on a match, add the diagonal too.
In code
ways[i][j] = ways[i - 1][j]
# skip this letter
Each box: ways to spell the first letters of t (across) from the first letters of s (down)
""rabbit
""
1
0
0
0
0
0
0
r
1
a
1
b
1
b
1
b
1
i
1
t
1

Column 0: the empty t can be spelled exactly one way from anything (use nothing). Row 0: an empty s can't spell anything longer.

Move 1 of 6
Quick check

A letter matches. There are 3 ways to spell the target that skip this letter, and 2 ways that use it. How many ways in total?

  1. A5
  2. B3
  3. C2
Show the answer

5. Both kinds of spelling exist, so add them: 3 + 2 = 5.

Your problem

Distinct subsequences

You get strings s and t. Return in how many different ways t can be spelled out by picking letters of s in order: the number of different sets of positions in s that read as t.

Example
s = "rabbbit", t = "rabbit" → 3

0 ≤ s.length, t.length ≤ 1,000 · lowercase English letters · return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve