RECURSION & BACKTRACKING › RECURSION PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Every even index has exactly 5 legal digits, while every odd index has exactly 4 legal digits. The choice made at one position does not restrict any other position, so you multiply the number of choices across all positions instead of constructing the strings one by one. Leading zeros being allowed means index 0 has the same five choices as every other even index.
Among the indices from 0 through n - 1, the even indices are 0, 2, 4, and so on, giving (n + 1) / 2 positions using integer division. The remaining n / 2 positions are odd. Therefore the answer is 5 raised to the even-position count multiplied by 4 raised to the odd-position count. Since n can be as large as 10^15, compute both powers by squaring.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(log n) | Each modular-power loop removes one binary digit of its exponent, so each of the two exponents is processed in logarithmically many iterations. Every iteration performs only a constant number of arithmetic operations. |
| Space | O(1) extra | The algorithm stores only a fixed number of counters, bases, results, and the input value; it does not allocate memory proportional to n. The returned integer is required output and is excluded from extra space. |
#include <string>
using namespace std;
class Solution {
public:
int countGoodNumbers(string n) {
const long long MOD = 1000000007LL;
long long length = stoll(n);
long long even = (length + 1) / 2;
long long odd = length / 2;
long long evenWays = modPow(5, even, MOD);
long long oddWays = modPow(4, odd, MOD);
return static_cast<int>((evenWays * oddWays) % MOD);
}
private:
long long modPow(long long base, long long exponent, long long mod) {
long long result = 1;
base %= mod;
while (exponent > 0) {
if (exponent & 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exponent >>= 1;
}
return result;
}
};The position formulas are the part most tightly connected to the zero-based indexing: (length + 1) / 2 counts indices 0, 2, 4, and so on, while length / 2 counts indices 1, 3, 5, and so on. In modPow, result is multiplied only for set exponent bits; squaring base then prepares the next power of two without ever building the full power.