Count Good Numbers (LeetCode 1922): Solution and Explanation

Medium
Math
Recursion
Fast Exponentiation

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

  1. Count the slots: evens = (n + 1) // 2 and odds = n // 2.
  2. Write power(base, exp): start with result = 1. While exp > 0, if its low bit is 1 multiply result by base; then square base and shift exp right. Reduce modulo 10^9 + 7 after every multiplication.
  3. Return power(5, evens) * power(4, odds) % MOD.

Step-by-step example

n = 4
  1. Indices 0 and 2 are even, so evens = 2. Indices 1 and 3 are odd, so odds = 2.
  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.
  3. power(4, 2): bit 0 is 0, skip 4^1; square to 16. Bit 1 is 1, so result = 16.
  4. 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) % MOD
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Independent choices plus fast power O(log n)
Pair the indices O(log n)
Recursive fast power O(log n)
Multiply n times O(n)
Time

O(log n)

Each call to power runs once per bit of its exponent, about log2(n) times.

Space

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.