LeetCode 2539: Count the Number of Good Subsequences

Problem Description

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:

  1. Initialize an array dp of size 10, where dp[i] represents the count of good subsequences that end with digit i.
  2. Initialize two variables zeroCount and hasZero to keep track of the count of 0s and whether 0 is present in the input string.
  3. Iterate over the input string:
    • If the current character is '0', increment zeroCount.
    • Otherwise, update dp[char - '0'] to 1 and set hasZero to true.
  4. Iterate from 1 to n (where n is the maximum number possible):
    • For each digit i, update dp[i] to (dp[i] + dp[i] + hasZero) % mod.
  5. 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).

Solutions

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;
    }
}

Loading editor...