Count Good Numbers — LeetCode 1922 Python Solution

MediumRecursionMath
Problem
#1922
Reading time
2 min

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

Python
class Solution:
    def countGoodNumbers(self, n: int) -> int:
        mod = 10**9 + 7
        return pow(5, (n + 1) >> 1, mod) * pow(4, n >> 1, mod) % mod

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview