Distinct Subsequences II - Problem

Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 10^9 + 7.

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).

Input & Output

Example 1 — Basic Case
$ Input: s = "abc"
Output: 7
💡 Note: The distinct subsequences are: "a", "b", "c", "ab", "ac", "bc", "abc". Total = 7.
Example 2 — Duplicate Characters
$ Input: s = "aba"
Output: 6
💡 Note: The distinct subsequences are: "a", "b", "aa", "ab", "ba", "aba". Note that "a" appears twice in the string but is counted only once as a single character subsequence. Total = 6.
Example 3 — All Same Characters
$ Input: s = "aaa"
Output: 3
💡 Note: The distinct subsequences are: "a", "aa", "aaa". All single 'a' subsequences are the same. Total = 3.

Constraints

  • 1 ≤ s.length ≤ 2000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Distinct Subsequences II INPUT String s = "abc" a idx 0 b idx 1 c idx 2 All Non-Empty Subsequences: "a" "b" "c" "ab" "ac" "bc" "abc" Length: 3 characters All chars distinct Total: 2^3 - 1 = 7 ALGORITHM STEPS 1 Initialize DP dp[i] = count ending at i last[char] = -1 (not seen) 2 Process Each Char dp[i] = 2 * dp[i-1] + 1 (double + new single) 3 Remove Duplicates If char seen before: dp[i] -= dp[last[c]-1] + 1 4 Update last[char] Track position for duplicate removal DP Array Progress: i=0 'a': dp=1 i=1 'b': dp=2*1+1=3 i=2 'c': dp=2*3+1=7 FINAL RESULT Answer: 7 Distinct Subsequences: Length 1 (3): "a", "b", "c" Length 2 (3): "ab", "ac", "bc" Length 3 (1): "abc" OK - Verified! 3 + 3 + 1 = 7 Key Insight: For distinct characters: dp[i] = 2 * dp[i-1] + 1 (double existing + new single char). For duplicates: subtract subsequences counted when char last appeared to avoid over-counting. TutorialsPoint - Distinct Subsequences II | Optimal DP Solution O(n) Time, O(1) Space
Asked in
Amazon 25 Google 18 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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