Distinct Subsequences - Problem

Given two strings s and t, return the number of distinct subsequences of s which equals t.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

The test cases are generated so that the answer fits on a 32-bit signed integer.

Input & Output

Example 1 — Basic Case
$ Input: s = "rabbbit", t = "rabbit"
Output: 3
💡 Note: There are 3 ways to form "rabbit" from "rabbbit": r-a-b-b-b-i-t (skip 1st b), r-a-b-b-b-i-t (skip 2nd b), r-a-b-b-b-i-t (skip 3rd b)
Example 2 — No Match
$ Input: s = "babgbag", t = "bag"
Output: 5
💡 Note: Five ways to form "bag": b-a-g(1st), b-a-g(2nd), b-a-g(3rd), b-a-g(4th), b-a-g(5th) using different combinations of b, a, g characters
Example 3 — Edge Case
$ Input: s = "abc", t = "def"
Output: 0
💡 Note: No characters match between s and t, so no subsequences of s can form t

Constraints

  • 1 ≤ s.length, t.length ≤ 1000
  • s and t consist of English letters only

Visualization

Tap to expand
Distinct Subsequences - Space-Optimized DP INPUT s = "rabbbit" r a b b b i t t = "rabbit" r a b b i t 3 ways to choose 'bb' from 'bbb': ra[b][b]_it ra[b]_[b]it ra_[b][b]it 1D DP Array (size: len(t)+1) 1 0 0 0 0 0 0 Initial: dp[0]=1, rest=0 ALGORITHM STEPS 1 Initialize DP Array dp[0]=1 (empty matches) dp[1..n]=0 2 Iterate s chars For each char in s, update dp right-to-left 3 Update Rule if s[i]==t[j]: dp[j+1] += dp[j] 4 Return dp[len(t)] Final answer at last position of dp array DP Transition (right-to-left): j j+1 Update from right to avoid overwriting needed values Time: O(m*n) | Space: O(n) FINAL RESULT Final DP Array State: 1 1 1 3 3 3 3 Index: 0 1 2 3 4 5 6 Output = 3 dp[6] = 3 Verification: 3 distinct subsequences of "rabbbit" equal "rabbit" 1: rabb_it (skip 3rd b) 2: rab_bit (skip 2nd b) 3: ra_bbit (skip 1st b) OK Key Insight: Space-optimized DP uses a 1D array instead of 2D by iterating right-to-left through t for each character in s. When s[i] == t[j], we add dp[j] to dp[j+1], accumulating the count of ways to form each prefix of t. Right-to-left iteration prevents overwriting values still needed in the current iteration. O(n) space vs O(m*n). TutorialsPoint - Distinct Subsequences | Space-Optimized DP Approach
Asked in
Google 25 Amazon 18 Facebook 15 Microsoft 12
78.0K Views
Medium Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen