TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
The Avengers need to determine who is the strongest. Given a list of their strengths, find the maximum strength using a recursive approach without using the max
function.
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?
max
?
HAPPY CASE
Input: [88, 92, 95, 99, 97, 100, 94]
Output: 100
Explanation: The maximum strength among the Avengers is 100.
Input: [50, 75, 85, 60, 90]
Output: 90
Explanation: The maximum strength among the Avengers is 90.
EDGE CASE
Input: [10]
Output: 10
Explanation: There is only one strength value in the list, so the maximum is 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 Finding Maximum 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 `strengths` has only one element, return that element as the maximum.
2) Recursive case:
a) Call the function recursively on the rest of the list `strengths[1:]`.
b) Compare the first element `strengths[0]` with the maximum of the rest of the list.
c) Return the larger value.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def strongest_avenger(strengths):
if len(strengths) == 1:
return strengths[0]
else:
max_of_rest = strongest_avenger(strengths[1:])
return strengths[0] if strengths[0] > max_of_rest else max_of_rest
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
strongest_avenger
function with the input [88, 92, 95, 99, 97, 100, 94]
. The function should return 100 after recursively comparing each element.[50, 75, 85, 60, 90]
. The function should return 90 after recursively comparing each element.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(N)
where N
is the number of elements in the list. The function makes one recursive call per element, leading to linear time complexity.O(N)
due to the recursion stack. The depth of recursion is proportional to the number of elements in the list, leading to linear space usage.