Similar Problems
Similar Problems not available
Count Good Numbers - Leetcode Solution
Companies:
LeetCode: Count Good Numbers Leetcode Solution
Difficulty: Medium
Topics: math
Problem Statement:
A digit string is good if the sum of its digits is even or the product of its digits is odd.
Given an integer n, return the count of all good digit strings of length n. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1 Output: 5 Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8". Example 2:
Input: n = 4 Output: 400 Example 3:
Input: n = 50 Output: 564908303
Approach:
We can solve this problem using dynamic programming. Let's define two arrays:
even[i] - the number of good digit strings of length i whose sum of digits is even odd[i] - the number of good digit strings of length i whose product of digits is odd Let's start with i=1.
even[1] = 5 because we have five even digits (0, 2, 4, 6, 8). odd[1] = 5 because we have five odd digits (1, 3, 5, 7, 9).
Now let's move to i=2. We can use the values of even[1] and odd[1] to calculate even[2] and odd[2].
even[2] can be calculated as the sum of the number of good digit strings of length 1 that end with an even digit multiplied by 5. Why? Because we can append any even digit to the end of a good digit string of length 1 whose sum of digits is even and we get a good digit string of length 2 whose sum of digits is even. For example, if we have "0" in the previous step, we can append any even digit (0, 2, 4, 6, 8) to get "00", "02", "04", "06", "08" which are all good digit strings of length 2 whose sum of digits is even. Similarly, we can append any odd digit (1, 3, 5, 7, 9) to the end of a good digit string of length 1 whose product of digits is odd and we get a good digit string of length 2 whose product of digits is odd. So:
even[2] = 5 * odd[1] = 25 odd[2] = even[1] + 5 * even[1] = 30 Let's move to i=3 and calculate even[3] and odd[3]:
even[3] = 5 * odd[2] = 5 * (even[1] + 5 * even[1]) = 125 odd[3] = even[2] + 5 * even[2] = 175 And so on, we can keep calculating even[i] and odd[i] using the values of even[i-1] and odd[i-1] until we reach the target length n.
Finally, the answer is the sum of even[n] and odd[n] because any good digit string of length n either has a sum of digits that is even or a product of digits that is odd.
Below is the implementation of this approach:
class Solution { public int countGoodNumbers(long n) { long MOD = 1000000007; long[] even = new long[51]; long[] odd = new long[51]; even[1] = 5; odd[1] = 5; for (int i = 2; i <= n; i++) { even[i] = (5 * odd[i-1]) % MOD; odd[i] = (even[i-1] + 5 * even[i-1]) % MOD; } return (int) ((even[(int) n] + odd[(int) n]) % MOD); } }
Time Complexity: O(n)
Space Complexity: O(n)
Count Good Numbers Solution Code
1