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: s = "rabbbit", t = "rabbit"r a b b b i tSource string sr a b b i tTarget string tPath 1: r-a-b₁-b₂-i-tPath 2: r-a-b₁-b₃-i-tPath 3: r-a-b₂-b₃-i-tOutput: 3 distinct ways
Understanding the Visualization
1
Input
Source string s and target string t
2
Process
Count all ways to pick characters from s (in order) to form t
3
Output
Total number of distinct subsequences
Key Takeaway
🎯 Key Insight: When characters match, we can choose to include or skip them, creating a tree of possibilities that DP efficiently counts
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