Skip to problem
←

Distinct Subsequences

Hard 0 attempts

Given strings s and t, count the ways to select characters at strictly increasing indices in s so that they spell t. Characters may be skipped, but their order cannot change.

Two selections are distinct when they use different indices, even if the selected characters are identical. For example, s = "aaa" and t = "aa" has three selections: indices (0, 1), (0, 2), and (1, 2). Matching is case-sensitive.

Function contract

s and t are nonempty, case-sensitive strings of English letters.

Output: Return the number of increasing index selections from s whose characters form t.

Example 1

Input
s = "rabbbit"
t = "rabbit"
Output
3

Explanation: Choose any two of the three b positions in rabbbit. These three index selections all spell rabbit.

Example 2

Input
s = "babgbag"
t = "bag"
Output
5
Constraints
  • 1 <= s.length, t.length <= 1000
  • s and t consist of English letters
  • The final answer fits in a signed 32-bit integer.

DP

After processing a prefix of s, dp[j] counts ways to form the first j characters of t. Initialize dp[0] = 1 for the empty selection. When characters match, add the ways to form the shorter target prefix.

Update j from right to left so the current source character cannot be reused during the same iteration. Different index selections are counted separately.

javascript
function numDistinct(s, t) {
  const m = s.length,
    n = t.length;
  const dp = Array(n + 1).fill(0);
  dp[0] = 1;
  for (let i = 1; i <= m; i++) {
    for (let j = n; j >= 1; j--) {
      if (s[i - 1] === t[j - 1]) dp[j] += dp[j - 1];
    }
  }
  return dp[n];
}

Time: O(mn) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript