You are given two strings, s and t. Count the ways to pick letters from s, keeping their order, so that the picked letters spell t exactly. Two ways are different when they use a different set of positions in s, even if the letters look the same.
Return that count. The answer is guaranteed to fit in a 32-bit signed integer.
Example 1
Input: s = "aabb", t = "ab" Output: 4 Why: 2 choices of a, each followed by 2 choices of b
2 more examples and the constraints
Example 2
Input: s = "dogdog", t = "dog" Output: 4 Why: d-o-g can use positions 012, 015, 045 or 345
Example 3
Input: s = "abc", t = "abcd" Output: 0 Why: t is longer than s, so it can never be spelled
Constraints
- 1 ≤ length of s, length of t ≤ 1,000
- s and t contain only English letters, upper or lower case
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m·n)
- Bottom-up tableO(m·n)
- One row, right to leftO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for s and t of 1,000 letters | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m·n) | Passes; deep recursion, slow lookups | |
| Bottom-up table | O(m·n) | Passes; easy to explain | |
| One row, right to left | O(m·n) | Best; same speed, O(n) memory |
m = length of s, n = length of t.
Edge cases to test
- t longer than s. "abc" against "abcd" is 0 with no work needed.
- s equals t. There is exactly one way: use every letter.
- All the same letter. 1,000 a's against "aaa" is C(1000, 3) = 166,167,000, close to the 32-bit limit.
- Case matters. "A" and "a" are different letters, so "Aa" against "aa" is 0.
- Huge middle values. 1,000 a's against 500 a's then a b is 0, but the cells in the middle are astronomically large.
Common mistakes
- Walking j left to right in the one-row version, so one letter of s is used twice in the same way.
- Setting only
dp[0][0] = 1instead of the whole empty-t column, so later rows start from 0. - Using a 32-bit signed int in C++ for the table, which overflows on middle cells and is undefined behaviour.
How to talk through it
- 1Clarify. Do two ways count as different when they use different positions with the same letters? Is it case sensitive?
- 2Give the recursion. Skip s[i], or use it when it matches t[j]; add the two. Point out the repeated (i, j) pairs and add a memo.
- 3Build the table. dp[i][j] for prefixes; the empty t column is all 1s; each cell is above plus, on a match, above-left.
- 4Squeeze to one row. Only the row above is read, so keep one row and walk j right to left so the old values survive.
- 5Test out loud. Run t longer than s, s equal to t, and the all-same-letter case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?