TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
The court magician is practicing a spell that doubles its power with each incantation. Given an integer initial_power
and a non-negative integer n
, write a recursive function that doubles initial_power
n
times.
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
n
times.n
is 0?
initial_power
without any changes.HAPPY CASE
Input: initial_power = 5, n = 3
Output: 40
Explanation: 5 doubled 3 times: 5 -> 10 -> 20 -> 40
Input: initial_power = 7, n = 2
Output: 28
Explanation: 7 doubled 2 times: 7 -> 14 -> 28
EDGE CASE
Input: initial_power = 10, n = 0
Output: 10
Explanation: If no doubling is required, the initial power remains 10.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Exponentiation via Doubling, we want to consider the following approaches:
n
until n
reaches 0.Plan the solution with appropriate visualizations and pseudocode.
General Idea:
n
times, multiply the initial_power
by 2 and call the function recursively with n-1
.Recursive Approach:
1) Base case: If `n` is 0, return the `initial_power` as no further doubling is needed.
2) Recursive case:
a) Multiply the `initial_power` by 2.
b) Return the result of the function called with the updated `initial_power` and `n-1`.
⚠️ Common Mistakes
initial_power
in each recursive call.Implement the code to solve the algorithm.
def double_power(initial_power, n):
# Base case: No more doubling needed
if n == 0:
return initial_power
# Recursive case: Double the power and reduce n
return double_power(initial_power * 2, n - 1)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
double_power
function with the input (5, 3)
. The function should return 40
after doubling 5
three times.n = 0
. The function should return the initial_power
unchanged.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(N)
where N
is the number of times the power needs to be doubled. The function performs N
recursive calls.O(N)
due to the recursion stack. The depth of recursion is proportional to n
.