Count Good Numbers (LeetCode 1922): Solution and Explanation
A digit string is good when its even-indexed digits are even and its odd-indexed digits are prime. Return how many good strings of length n exist, modulo 10^9 + 7.
Intuition
Nothing links one index to another. The digit at index 0 does not limit the digit at index 1, so the count is a product of independent choices per index.
An even index can hold 0, 2, 4, 6 or 8, which is 5 choices. An odd index can hold 2, 3, 5 or 7, which is 4 choices. A string of length n has (n + 1) // 2 even indices and n // 2 odd ones, so the answer is 5^evens * 4^odds.
The exponents can be around a billion, so multiplying one factor at a time is far too slow. Fast exponentiation reads the exponent in binary. The base is squared at every step, so it walks through b^1, b^2, b^4, b^8, ..., and it is multiplied into the result only at the 1-bits. That needs about 31 steps instead of a billion.
Approach: Independent choices plus fast power
- Count the slots:
evens = (n + 1) // 2andodds = n // 2. - Write
power(base, exp): start withresult = 1. Whileexp > 0, if its low bit is 1 multiplyresultbybase; then squarebaseand shiftexpright. Reduce modulo10^9 + 7after every multiplication. - Return
power(5, evens) * power(4, odds) % MOD.
Step-by-step example
n = 4
- Indices 0 and 2 are even, so evens = 2. Indices 1 and 3 are odd, so odds = 2.
- power(5, 2): exp = 10 in binary. Bit 0 is 0, so skip 5^1; square the base to 25. Bit 1 is 1, so result = 25.
- power(4, 2): bit 0 is 0, skip 4^1; square to 16. Bit 1 is 1, so result = 16.
- Multiply: 25 * 16 = 400. Return 400.
Code: Python, Java, C++
1class Solution:
2 def countGoodNumbers(self, n: int) -> int:
3 MOD = 10**9 + 7
4 def power(base: int, exp: int) -> int:
5 result = 1
6 while exp > 0:
7 if exp & 1:
8 result = result * base % MOD
9 base = base * base % MOD
10 exp >>= 1
11 return result
12 evens = (n + 1) // 2
13 odds = n // 2
14 return power(5, evens) * power(4, odds) % MOD1class Solution {
2 private static final long MOD = 1_000_000_007L;
3 public int countGoodNumbers(int n) {
4 long evens = (n + 1L) / 2;
5 long odds = n / 2;
6 return (int) (power(5, evens) * power(4, odds) % MOD);
7 }
8 private long power(long base, long exp) {
9 long result = 1;
10 while (exp > 0) {
11 if ((exp & 1) == 1) {
12 result = result * base % MOD;
13 }
14 base = base * base % MOD;
15 exp >>= 1;
16 }
17 return result;
18 }
19}1class Solution {
2public:
3 int countGoodNumbers(int n) {
4 long long evens = (n + 1LL) / 2;
5 long long odds = n / 2;
6 return (int) (power(5, evens) * power(4, odds) % MOD);
7 }
8private:
9 static const long long MOD = 1000000007LL;
10 long long power(long long base, long long exp) {
11 long long result = 1;
12 while (exp > 0) {
13 if (exp & 1) {
14 result = result * base % MOD;
15 }
16 base = base * base % MOD;
17 exp >>= 1;
18 }
19 return result;
20 }
21};Time and space complexity
O(log n)
Each call to power runs once per bit of its exponent, about log2(n) times.
O(1)
The iterative power keeps only base, exp and result.
Other approaches
Pair the indices (time O(log n), space O(1))
Each pair of positions (even, odd) contributes 5 * 4 = 20 choices. Compute 20^(n // 2) and multiply by 5 once more when n is odd. Same O(log n) cost with one power call.
Recursive fast power (time O(log n), space O(log n))
power(b, e) = power(b, e // 2)^2, times b when e is odd. It is the same idea written top down and uses O(log n) stack frames.
Multiply n times (time O(n), space O(1))
Loop over every index and multiply by 5 or 4. Correct, but a billion iterations is too slow for large n.
Common mistakes
- Overflow inside the power loop. base * base can reach about 10^18, so use 64-bit integers in Java, C++, C# and Go, and split the multiplication in JavaScript, where doubles lose precision above 2^53.
- Mixing up the counts of even and odd indices. Index 0 is even, so a string of odd length has one more even index than odd.
- Treating 0 as not even or 1 as prime. Even digits are 0, 2, 4, 6, 8 and prime digits are 2, 3, 5, 7.
- Computing (n + 1) / 2 in 32-bit arithmetic when n = 2^31 - 1, which overflows. Widen to 64 bits first.
Frequently asked questions
Why are leading zeros allowed to count?
The problem counts digit strings, not integers, so "04" is a valid length-2 string. That is why 0 is one of the 5 choices at index 0.
How does fast exponentiation work here?
Write the exponent in binary. The base takes the values b, b^2, b^4, b^8 and so on, one per bit, by squaring. Multiplying together the ones whose bit is 1 gives b raised to the full exponent.
Why does this page use a 32-bit n?
LeetCode allows n up to 10^15, which needs a 64-bit parameter. The judge here passes n as a 32-bit int, so tests stop at 2^31 - 1. The algorithm is the same for larger n.
Can I use the built-in pow?
In Python, pow(5, evens, MOD) does exactly this. Other languages have no modular pow in the standard library, so write the loop.