LeetCode 1987: Number of Unique Good Subsequences Solution
Master LeetCode problem 1987 (Number of Unique Good Subsequences), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1987. Number of Unique Good Subsequences
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We need to keep track of the number of unique good subsequences ending with '0' and '1'.
- Create two variables to store the count of subsequences ending with '0' and '1'.
- Traverse the binary string.
- If the current character is '0', update the count of subsequences ending with '0' as the sum of the count of subsequences ending with '0' and '1' (since we can append '0' to any good subsequence ending with '0' or '1').
- If the current character is '1', update the count of subsequences ending with '1' as the sum of the count of subsequences ending with '0' and '1' (similar to the case of '0').
- Keep track of whether '0' and '1' have been encountered at least once.
- If both '0' and '1' have been encountered, add 1 to the total count to account for the empty subsequence.
Finally, return the sum of subsequences ending with '0' and '1' along with the additional count if both '0' and '1' have been encountered.
Time Complexity: O(n) where n is the length of the binary string. Space Complexity: O(1)
Solution Code
class Solution {
public int numberOfUniqueGoodSubsequences(String binary) {
final int MOD = 1000000007;
int endWith0 = 0;
int endWith1 = 0;
boolean has0 = false;
boolean has1 = false;
for (char c : binary.toCharArray()) {
if (c == '0') {
endWith0 = (endWith0 + endWith1) % MOD;
has0 = true;
} else {
endWith1 = (endWith0 + endWith1 + 1) % MOD;
has1 = true;
}
}
return (endWith0 + endWith1 + (has0 && has1 ? 1 : 0)) % MOD;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1987 (Number of Unique Good Subsequences)?
This page provides optimized solutions for LeetCode problem 1987 (Number of Unique Good Subsequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1987 (Number of Unique Good Subsequences)?
The time complexity for LeetCode 1987 (Number of Unique Good Subsequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1987 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1987 in Java, C++, or Python.