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?
amount
units of supplies.-1
.0
, Zuko doesn't need any tokens and the result should be 0
.HAPPY CASE
Input:
tokens = [1, 2, 5], amount = 11
Output:
3
Explanation:
Zuko can gather 11 units of supplies with 5 + 5 + 1 tokens.
EDGE CASE
Input:
tokens = [2], amount = 3
Output:
-1
Explanation:
It's impossible for Zuko to gather exactly 3 units of supplies with only 2-unit tokens.
EDGE CASE
Input:
tokens = [1], amount = 0
Output:
0
Explanation:
Zuko doesn't need any tokens to gather 0 units of supplies.
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 minimum token problems, we want to consider the following approaches:
i
units of supplies.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use dynamic programming to calculate the minimum number of tokens needed to gather the exact amount. We will build up a solution using a DP array, where dp[i]
stores the minimum number of tokens required to gather exactly i
units of supplies.
Base Case:
dp
initialized to float('inf')
, except dp[0] = 0
since 0 units can be gathered with 0 tokens.Token Processing:
tokens
, iterate over all possible supply amounts from token
to amount
.i
, calculate dp[i]
as the minimum of the current value dp[i]
and dp[i - token] + 1
.Return Result:
dp[amount]
is still float('inf')
, return -1
, indicating it's impossible to gather the exact amount.dp[amount]
.Implement the code to solve the algorithm.
def zuko_supply_mission(tokens, amount):
# Initialize DP array with infinity, except dp[0] = 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0
# Update dp array for each token
for token in tokens:
for i in range(token, amount + 1):
dp[i] = min(dp[i], dp[i - token] + 1)
# If dp[amount] is still infinity, it means the amount cannot be achieved
return dp[amount] if dp[amount] != float('inf') else -1
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
tokens = [1, 2, 5], amount = 11
3
Example 2:
tokens = [2], amount = 3
-1
Example 3:
tokens = [1], amount = 0
0
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n
is the amount and m
is the number of tokens.
O(n * m)
because we iterate over each amount from 1
to n
for each token in tokens
.O(n)
to store the DP array.