115. Distinct Subsequences
Asked at 11Amazon38Bloomberg36Microsoft33Google33Meta32Swiggy100Meesho67Salesforce61Coupang58Zoho42tcs27
Problem
Count the distinct ways to pick a subsequence of s (a set of positions) that spells t.
Example: s = "rabbbit", t = "rabbit" → 3; s = "babgbag", t = "bag" → 5
Constraints: lengths ≤ 1000; the answer fits in 32 bits.
dp[i][j] = ways s[:i] contains t[:j] as a subsequence = dp[i−1][j] (skip s[i−1]) + dp[i−1][j−1] if chars match. 1-D: iterate j downward.
Complexity: O(m·n) time, O(n) space.
class Solution:
def numDistinct(self, s: str, t: str) -> int:
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]
assert Solution().numDistinct("rabbbit", "rabbit") == 3
assert Solution().numDistinct("babgbag", "bag") == 5
class Solution {
public int numDistinct(String s, String t) {
long[] dp = new long[t.length() + 1];
dp[0] = 1;
for (char ch : s.toCharArray())
for (int j = t.length(); j > 0; j--)
if (t.charAt(j - 1) == ch) dp[j] += dp[j - 1];
return (int) dp[t.length()];
}
}
func numDistinct(s string, t string) int {
dp := make([]int, len(t)+1) // dp[j] = ways to form t[:j] from the prefix of s seen so far
dp[0] = 1
for i := 0; i < len(s); i++ {
for j := len(t); j > 0; j-- { // backwards so s[i] is used once per subsequence
if t[j-1] == s[i] {
dp[j] += dp[j-1]
}
}
}
return dp[len(t)]
}