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: 4
💡 Note: The distinct subsequences are: "a", "b", "ab", "ba", "aba". Note that "a" appears twice in the string but is counted only once. Total = 4.
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: From String to CountInput String"aba"Build Subsequences"a""b""ab""ba""aba"Handle duplicates: "a" counted onceOutput4
Understanding the Visualization
1
Input
String with possible duplicate characters
2
Process
Build subsequences while tracking character occurrences
3
Output
Count of distinct non-empty subsequences
Key Takeaway
🎯 Key Insight: Use DP to track character counts and subtract duplicates when the same character appears again
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