#1922

Count Good Numbers

Medium
MathRecursionCombinatorial CountingFast Exponentiation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of generating all strings, we can use combinatorial counting. For even indices, we have 5 choices (0, 2, 4, 6, 8) and for odd indices, we have 4 choices (2, 3, 5, 7). We can calculate the total number of good strings using powers of these choices.

⚙️

Algorithm

3 steps
  1. 1Step 1: Determine the number of even and odd indices based on n.
  2. 2Step 2: Calculate the number of good strings as (5^(even_count) * 4^(odd_count)) % (10^9 + 7).
  3. 3Step 3: Use fast exponentiation to compute powers efficiently.
solution.py14 lines
1def countGoodNumbers(n):
2    MOD = 10**9 + 7
3    even_count = (n + 1) // 2
4    odd_count = n // 2
5    def power(x, y, p):
6        res = 1
7        x = x % p
8        while y > 0:
9            if (y & 1):
10                res = (res * x) % p
11            y //= 2
12            x = (x * x) % p
13        return res
14    return (power(5, even_count, MOD) * power(4, odd_count, MOD)) % MOD

Complexity note: The time complexity is O(log n) due to the fast exponentiation method, which reduces the number of multiplications needed to compute powers.

  • 1Good numbers have a specific structure based on the index of digits.
  • 2Using combinatorial counting allows us to avoid generating all possible strings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.