Count of Good Numbers leetcode :- 1922
Optimized Count of Good Numbers | O(log n) Solution š
Introduction
Counting "Good Numbers" is an interesting problem that requires us to efficiently compute large exponentiations while following specific digit placement rules. This blog post explores an optimized approach using modular exponentiation, breaks down the logic, and provides a dry run for better understanding.
Problem Statement
Given an integer n
, we need to find how many valid numbers of length n
can be formed such that:
- Digits at even indices (0-based) must be even (0, 2, 4, 6, 8) → 5 choices
- Digits at odd indices must be prime (2, 3, 5, 7) → 4 choices
Since the result can be large, we return it modulo 10⁹ + 7.
Optimized Approach
To construct such numbers, we can observe:
- Even-indexed positions contribute
5^(odd_count)
- Odd-indexed positions contribute
4^(even_count)
Where:
even_count = n // 2
(number of even-indexed positions)odd_count = n - even_count
(number of odd-indexed positions)
Thus, the final answer is:
(5^(odd_count) * 4^(even_count)) % (10^9 + 7)
Efficient Computation using Binary Exponentiation
Instead of computing large powers directly, we use binary exponentiation which computes x^n
in O(log n)
time.
Code Implementation
class Solution: def countGoodNumbers(self, n: int) -> int: MOD = 10 ** 9 + 7 even_count, odd_count = n // 2, n - n // 2 even_part = self.power(4, even_count, MOD) odd_part = self.power(5, odd_count, MOD) return even_part * odd_part % MOD def power(self, x: int, n: int, MOD: int) -> int: if x == 0: return 0 if n == 0: return 1 result = self.power(x, n // 2, MOD) result = result * result if n % 2 == 1: return x * result % MOD return result % MOD
Dry Run Example
Let’s walk through an example where n = 4
.
Step 1: Compute Counts
even_count = 4 // 2 = 2 odd_count = 4 - 2 = 2
Step 2: Compute Powers
odd_part = 5^2 = 25 even_part = 4^2 = 16
Step 3: Compute Result Modulo 10⁹ + 7
(25 * 16) % (10^9 + 7) = 400
Final Answer
400
Complexity Analysis
- Binary exponentiation runs in
O(log n)
, making the solution very efficient. - Overall complexity:
O(log n)
.
Conclusion
By breaking the problem into modular exponentiation, we achieve an optimized O(log n)
solution. This approach ensures efficiency even for large values of n
.
LeetCode Solution Link
Check out my detailed solution on LeetCode: Optimized Count of Good Numbers | O(log n) š
Comments
Post a Comment