#1987

Number of Unique Good Subsequences

Hard
StringDynamic ProgrammingDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(2^n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to count unique good subsequences efficiently by leveraging previously computed results. This avoids the need to generate all subsequences explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i] represents the number of unique good subsequences ending at index i.
  2. 2Step 2: Iterate through the binary string, updating the DP array based on whether the current character is '0' or '1'.
  3. 3Step 3: Use a last occurrence map to handle duplicates and ensure uniqueness.
solution.py14 lines
1def uniqueGoodSubseq(binary):
2    MOD = 10**9 + 7
3    n = len(binary)
4    dp = [0] * (n + 1)
5    last = {'0': -1, '1': -1}
6    dp[0] = 1
7    for i in range(1, n + 1):
8        dp[i] = (2 * dp[i - 1]) % MOD
9        if binary[i - 1] == '0':
10            dp[i] = (dp[i] - (dp[last['0']] if last['0'] != -1 else 0)) % MOD
11        else:
12            dp[i] = (dp[i] - (dp[last['1']] if last['1'] != -1 else 0)) % MOD
13        last[binary[i - 1]] = i - 1
14    return (dp[n] - 1) % MOD

Complexity note: The time complexity is O(n) because we iterate through the string once, updating our DP array. The space complexity is O(n) for storing the DP values.

  • 1Good subsequences must not have leading zeros unless they are '0'.
  • 2Dynamic programming can efficiently count subsequences by building on previous results.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.