Count Good Numbers — LeetCode 1922 Python Solution
- Problem
- #1922
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime.
Example
- Input
- n = 1
- Output
- 5
- Explanation
- The good numbers of length 1 are "0", "2", "4", "6", "8".
Python solution
class Solution:
def countGoodNumbers(self, n: int) -> int:
mod = 10**9 + 7
return pow(5, (n + 1) >> 1, mod) * pow(4, n >> 1, mod) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1922. Count Good Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1922. Count Good Numbers?
- LeetCode 1922. Count Good Numbers is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1922. Count Good Numbers?
- The Python solution on this page runs in O(\log n).
- What is the space complexity of LeetCode 1922. Count Good Numbers?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1922. Count Good Numbers cover?
- LeetCode 1922. Count Good Numbers is tagged Recursion and Math on LeetCode.