TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
Thanos is collecting Infinity Stones. Given an array of integers stones
representing the power of each stone, return the total power using a recursive approach.
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?
HAPPY CASE
Input: [5, 10, 15, 20, 25, 30]
Output: 105
Explanation: The sum of the stones' power is 5 + 10 + 15 + 20 + 25 + 30 = 105.
Input: [12, 8, 22, 16, 10]
Output: 68
Explanation: The sum of the stones' power is 12 + 8 + 22 + 16 + 10 = 68.
EDGE CASE
Input: []
Output: 0
Explanation: The list is empty, so the sum should be 0.
Input: [100]
Output: 100
Explanation: The list has only one stone with power 100.
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 Summation Problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Recursive Approach:
1) Base case: If the list `stones` is empty, return 0.
2) Recursive case: Return the first element of `stones` plus the result of a recursive call to the same function with the rest of the list (excluding the first element).
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def collect_infinity_stones(stones):
if not stones:
return 0
return stones[0] + collect_infinity_stones(stones[1:])
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
collect_infinity_stones
function with the input [5, 10, 15, 20, 25, 30]
. The function should return 105 after six recursive calls.[12, 8, 22, 16, 10]
. The function should return 68 after five recursive calls.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of stones in the list.
O(N)
where N
is the number of stones in the list. This is because the function makes one recursive call per stone in the list, summing them up in linear time.O(N)
due to the recursion stack. Each recursive call adds a new frame to the stack, leading to linear space usage proportional to the number of stones.