Unit 12 Session 1 Standard (Click for link to problem statements)
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:
n = 5
Output:
5
Explanation:
The energy gained on day 5 is the sum of the energy on days 3 and 4 (2 + 3 = 5).
EDGE CASE
Input:
n = 1
Output:
1
Explanation:
On the first day, Aang gains 1 unit of energy.
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 energy balance problems, we want to consider the following approaches:
n
depends on the sum of the energy from the two previous days.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use dynamic programming to compute the energy Aang gains on day n
. We start with base cases for days 1 and 2, where Aang gains 1 unit of energy, and for each subsequent day, we calculate the energy as the sum of the previous two days.
Base Case:
Dynamic Programming Array:
dp
where dp[i]
stores the energy gained on day i
.Recurrence Relation:
i
from 3 to n
, calculate dp[i]
as the sum of dp[i - 1]
and dp[i - 2]
.Return the Result:
dp[n]
will give the energy gained on day n
.Implement the code to solve the algorithm.
def energy_on_nth_day(n):
# Base case for days 1 and 2, Aang gains 1 unit of energy
if n == 1 or n == 2:
return 1
# Create a dp array to store the energy Aang gains on each day
dp = [0] * (n + 1)
# Initial energy gains for day 1 and day 2
dp[1] = 1
dp[2] = 1
# For each day from 3 to n, calculate energy as the sum of the previous two days
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
# Return the energy gained on day n
return dp[n]
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
n = 5
5
Example 2:
n = 1
1
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n
is the input number of days.
O(n)
because we calculate the energy for each day up to n
.O(n)
to store the DP array with n
elements.