LeetCode 2539: Count the Number of Good Subsequences Solution
Master LeetCode problem 2539 (Count the Number of Good Subsequences), a medium 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.
2539. Count the Number of Good Subsequences
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. The key idea is to keep track of the counts of good subsequences that end with a certain digit (0 to 9) and whether or not a digit is present in the input string.
Here are the steps:
- Initialize an array
dpof size 10, wheredp[i]represents the count of good subsequences that end with digiti. - Initialize two variables
zeroCountandhasZeroto keep track of the count of 0s and whether 0 is present in the input string. - Iterate over the input string:
- If the current character is '0', increment
zeroCount. - Otherwise, update
dp[char - '0']to1and sethasZerototrue.
- If the current character is '0', increment
- Iterate from 1 to n (where n is the maximum number possible):
- For each digit
i, updatedp[i]to(dp[i] + dp[i] + hasZero) % mod.
- For each digit
- Finally, add 1 to the total count if there is at least one '0' in the input string.
The final count of good subsequences will be the sum of all counts in the dp array.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1) since the dp array is of constant size (10).
Solution Code
class Solution {
public int countGoodSubsequences(String s) {
int mod = 1000000007;
int[] dp = new int[10];
int zeroCount = 0;
boolean hasZero = false;
for (char c : s.toCharArray()) {
if (c == '0') {
zeroCount++;
} else {
dp[c - '0'] = 1;
hasZero = true;
}
}
for (int i = 1; i < 10; i++) {
dp[i] = (dp[i] + dp[i] + (hasZero ? 1 : 0)) % mod;
}
return (Arrays.stream(dp).sum() + (zeroCount > 0 ? 1 : 0)) % mod;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2539 (Count the Number of Good Subsequences)?
This page provides optimized solutions for LeetCode problem 2539 (Count the Number of 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 2539 (Count the Number of Good Subsequences)?
The time complexity for LeetCode 2539 (Count the Number of 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 2539 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2539 in Java, C++, or Python.