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: 2
💡 Note: All subsequences: ["1", "1", "11"]. All are good. Unique good subsequences: ["1", "11"] = 2
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 INPUT Binary String: 0 idx 0 0 idx 1 1 idx 2 binary = "001" Good Subsequences: "0" "1" Invalid (leading zeros): "01" "001" ALGORITHM STEPS 1 Initialize DP ends0=0, ends1=0 hasZero=false 2 Process Each Bit If bit='1': ends1 = ends0 + ends1 + 1 3 Handle Zero Bit If bit='0': ends0 = ends0 + ends1 Set hasZero = true 4 Compute Result result = ends0 + ends1 Add 1 if hasZero DP Trace for "001": i=0: ends0=0, ends1=0 i=1: ends0=0, ends1=0 i=2: ends0=0, ends1=1 FINAL RESULT Unique Good Subsequences: "0" Standalone zero "1" Starts with 1 Output: 2 OK - Verified Key Insight: Track subsequences ending in 0 and 1 separately. The standalone "0" must be handled specially since sequences starting with 0 (except "0" itself) are invalid due to leading zeros. Time: O(n), Space: O(1). Use modulo 10^9+7 for large results. TutorialsPoint - Number of Unique Good Subsequences | Optimized DP with Special Zero Handling
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