Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the number of distinct subsequences of s that equal t.

Problem: Count the number of distinct subsequences of s that equal t.
def distinct(s, t):
    dp = [1] + [0] * len(t)
    for ch in s:
        for j in range(len(t), 0, -1):
            if t[j - 1] == ch: dp[j] += dp[j - 1]
    return dp[-1]
print(distinct("rabbbit", "rabbit"), distinct("babgbag", "bag"))
What is printed?
  1. A. 3 4
  2. B. 2 5
  3. C. 6 5
  4. D. 3 5

Correct answer: D. 3 5

dp[j] = ways to form t[:j] from the processed prefix of s. Iterating j downwards ensures each character of s is used at most once per subsequence (like the 0/1 knapsack). "rabbbit" drops one of three b's → 3; "babgbag" → 5. O(|s|·|t|).

More Coding Interview Problems questions

Exams that ask this topic