Distinct Subsequences

Difficulty: Hard

Given strings s and t, count the distinct subsequences of s (delete some characters, keep the rest in order) that spell t exactly.

Two ways differ if they delete different characters from s, even if the remaining letters look the same.

Examples

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

There are 3 ways to delete two of the three b's from s to spell out rabbit.

Input: s = "babgbag", t = "bag"
Output: 5

Constraints

  • 1 <= s.length, t.length <= 1000

  • Both strings contain only English letters

Approach

Cell (i, j) is the number of ways the first i characters of s can spell the first j characters of t.

The i-th character of s can always be skipped, giving the ways in (i-1, j). If it also equals the j-th character of t, it can be used to match it, adding the ways in (i-1, j-1). The two sets of deletions are different, so they don't overlap — just add them.

Base case: an empty t (column 0) matches any prefix of s in exactly one way — delete everything.

Solutions

Brute Force — Recursion

Walk s and t together from the front. Always try skipping the current character of s; if it matches the current character of t, also try using both. Sum the ways from each branch.

function numDistinct(s, t) {
  function solve(i, j) {
    if (j === t.length) return 1;
    if (i === s.length) return 0;

    let ways = solve(i + 1, j); // skip s[i]
    if (s[i] === t[j]) {
      ways += solve(i + 1, j + 1); // use s[i] to match t[j]
    }
    return ways;
  }

  return solve(0, 0);
}

Time: O(2^m), where m is the length of s · Space: O(m) — recursion depth

Optimal — Bottom-Up 2D Table

Build a table over (prefix length of s, prefix length of t). Column 0 is 1 (an empty t matches one way); every other cell is 'skip' plus, when characters match, 'use.'

function numDistinct(s, t) {
  const m = s.length;
  const n = t.length;
  const table = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));

  for (let i = 0; i <= m; i++) {
    table[i][0] = 1; // empty t is always formed exactly one way: delete everything
  }

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      table[i][j] = table[i - 1][j]; // skip s[i - 1]
      if (s[i - 1] === t[j - 1]) {
        table[i][j] += table[i - 1][j - 1]; // also use s[i - 1] to match t[j - 1]
      }
    }
  }

  return table[m][n];
}

Time: O(m * n) · Space: O(m * n)