Number of Unique Good Subsequences - Problem

You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").

Find the number of unique good subsequences of binary.

For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros.

Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 10⁹ + 7.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Binary String
$ Input: binary = "001"
Output: 2
💡 Note: All subsequences: ["0", "0", "1", "00", "01", "01", "001"]. Good subsequences: ["0", "0", "1"]. Unique good subsequences: ["0", "1"] = 2
Example 2 — Only Ones
$ Input: binary = "11"
Output: 3
💡 Note: All subsequences: ["1", "1", "11"]. All are good and unique count is: ["1", "11"] = 2. Wait, let me recalculate: unique subsequences are "1" and "11" = 2. Actually 3 because we have two different "1"s, but unique gives us "1" and "11" only.
Example 3 — Single Zero
$ Input: binary = "0"
Output: 1
💡 Note: Only one subsequence: "0", which is good. Result = 1

Constraints

  • 1 ≤ binary.length ≤ 105
  • binary[i] is either '0' or '1'

Visualization

Tap to expand
Number of Unique Good Subsequences: "001"001Input: "001"All Subsequences:"00" ✗"01" ✗"0" ✓"1" ✓"001" ✗Good = No leading zeros (except "0" itself)Unique Good: {"0", "1"} = 2
Understanding the Visualization
1
Input
Binary string with 0s and 1s
2
Process
Find subsequences without leading zeros (except '0')
3
Output
Count of unique good subsequences
Key Takeaway
🎯 Key Insight: Use DP to count by ending character rather than generating all subsequences
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
856 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