Count Good Numbers
LeetCode 1922 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
5^ceil(n/2) · 4^floor(n/2) mod 1e9+7.
मी Count Good Numbers (LeetCode 1922) असा सोडवला — Recursion Basics पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Even positions can hold 5 digits (0, 2, 4, 6, 8) and odd positions 4 digits (2, 3, 5, 7), independently. So the count is 5^(even positions) × 4^(odd positions), computed with fast modular exponentiation.
Approach
- 1
Backtracking version: build every string — only works for tiny n.
- 2
Even indices: (n + 1) // 2; odd indices: n // 2.
- 3
Fast power mod 1e9+7 for both, then multiply.
मी कसा सोडवला · पहिल्या कल्पनेपासून अंतिम उपायापर्यंत
Enumerate every good string.
Counting formula.
BacktrackingPythonO(5^n) time
class Solution:
def countGoodNumbers(self, n: int) -> int:
#0,2,4,6,8 - length 1
#0/2/4/6/8_ 2/3/5/7_ 02,03,05,07 22 23 25 27
#if index is even pick even no
#if index is odd pick odd no
count = 0
def dfs(index,ds):
nonlocal count
if len(ds)==n:
count+=1
return
if index%2==0:
nums = ["0","2","4","6","8"]
for num in nums:
ds.append(num)
dfs(index+1,ds)
ds.pop()
elif index%2==1:
nums = ["2","3","5","7"]
for num in nums:
ds.append(num)
dfs(index+1,ds)
ds.pop()
dfs(0,[])
return countFast modular powerPythonO(log n) time
class Solution:
def countGoodNumbers(self, n: int) -> int:
#0,2,4,6,8 - 5 at even indices
#2,3,5,7 - 4 at odd indices
#01234 - a number of length 5 has 5+1/2 even indices - 3 indices[0,2,4], 5//2 - 2 odd indices - 1,3
#total of good numbers of string of length n is - 5^(n+1)//2*4^(n//2)
mod = 10**9+7
def calculate_pow(x,y):
x=x%mod
ans = 1
while y>0:
if y%2==1:
ans = (ans*x)%mod
y = y-1
else:
x = (x*x)%mod
y = y//2
return ans
return (calculate_pow(5,(n+1)//2)*calculate_pow(4,n//2))%modCount Good Numbers — वारंवार विचारले जाणारे प्रश्न
Count Good Numbers मागील intuition काय आहे?
Even positions can hold 5 digits (0, 2, 4, 6, 8) and odd positions 4 digits (2, 3, 5, 7), independently. So the count is 5^(even positions) × 4^(odd positions), computed with fast modular exponentiation.
Count Good Numbers (LeetCode 1922) कसा सोडवावा?
1. Backtracking version: build every string — only works for tiny n. 2. Even indices: (n + 1) // 2; odd indices: n // 2. 3. Fast power mod 1e9+7 for both, then multiply.
Count Good Numbers ची time आणि space complexity किती आहे?
Time: O(log n). Space: O(1). (Accepted approach: Fast modular power.)
Count Good Numbers मध्ये सामान्य चुका कोणत्या?
n can be 10¹⁵ — exponentiation by squaring is required. The brute-force version doesn't take the modulo, so it disagrees for large n.
Count Good Numbers सोडवण्याचे एकापेक्षा जास्त मार्ग आहेत का?
Backtracking (O(5^n) time): Enumerate every good string. Fast modular power (O(log n) time): Counting formula.