Lecture 1 : Get a strong hold¶
Count Good numbers¶
A digit string is considered good if the digits at even indices (0-based) are even digits (0, 2, 4, 6, 8) and the digits at odd indices are prime digits (2, 3, 5, 7). Given an integer n, return the total number of good digit strings of length n. As the result may be large, return it modulo 109 + 7. A digit string is a string consisting only of the digits '0' through '9'. It may contain leading zeros.
Example 1:
Input: n = 1
Output: 5
Explanation: Only one index (0) → must be even.
Valid strings: "0", "2", "4", "6", "8"
Example 2:
Input: n = 2
Output: 20
Explanation: Index 0: 5 options (even digits)
Index 1: 4 options (prime digits)
Total: 5 * 4 = 20
Input n=4
Output = 400
Input n=50
Output = 564908303
Approach 1 (Recursive )¶
- count_good(1) = 5
- count_good(n) =
- 4 * count_good(n-1) when n is even
- 5 * count_good(n-1) when n is odd
def count_good(n):
MOD = 10**9 + 7
if n==1:
return 5
if n% 2 ==0:
return (4 * count_good(n-1)) % MOD
return (5 * count_good(n-1)) % MOD
print(count_good(1))
print(count_good(2))
print(count_good(3))
print(count_good(50))
5 20 100 564908303
Complexity¶
- > O(N)
- > O(N)
> It will cause stack overflow for long input
1 <= n <= 1015
Approach 2 (Iteration )¶
- count(1) = 5 and count (2) = 5*4 = 20
- count (n) = even_digits ** 5 * odd_digits ** 4
def count_good(n):
if n ==1 :
return 5
if n ==2 :
return 5 * 4
MOD = 10 **9 + 7
even_positions = (n +1) // 2
odd_positions = (n //2)
even_ways = pow(5,even_positions,MOD)
odd_ways = pow(4,odd_positions,MOD)
return (even_ways * odd_ways) % MOD
print(count_good(1))
print(count_good(2))
print(count_good(3))
print(count_good(50))
5 20 100 564908303
Complexity¶
O(log n ) : pow(base,exponent,MOD) : exponentiation by squaring : O(log expoponent)
O(1)
Reverse a stack using recursion¶
You are given a stack of integers. Your task is to reverse the stack using recursion. You may only use standard stack operations (push, pop, top/peek, isEmpty). You are not allowed to use any loop constructs or additional data structures like arrays or queues.
Input: stack = [4, 1, 3, 2]
Output: [2, 3, 1, 4]
Input: stack = [10, 20, -5, 7, 15]
Output: [15, 7, -5, 20, 10]
Approach 1 (Recursion)¶
def reverse_stack(stack):
if len(stack) <=1:
return stack
def insert_at_bottom(stack,element):
if len(stack) ==0:
stack.append(element)
return
top = stack.pop()
insert_at_bottom(stack,element)
stack.append(top)
top = stack.pop()
reverse_stack(stack)
insert_at_bottom(stack,top)
return stack
print(reverse_stack([4,1,3,2]))
print(reverse_stack([10,20,-5,7,15]))
[2, 3, 1, 4] [15, 7, -5, 20, 10]
Complexity¶
O(N^2) : N = len(stack)
O(N) : N = len(stack)