Understand what the interviewer is asking for by using test cases and questions about the problem.
gold_amounts
of integers representing the gold amounts at each location, and an integer target
.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a hashmap to keep track of the indices of gold amounts as we iterate through the list. For each gold amount, calculate the complement (the amount needed to reach the target) and check if it has already been seen.
1) Initialize an empty dictionary `gold_map` to store the gold amounts and their corresponding indices.
2) Iterate through the `gold_amounts` array using an index `i`:
- Calculate the complement of the current gold amount (`target - amount`).
- If the complement exists in `gold_map`, return the indices of the complement and the current location.
- Otherwise, store the current gold amount with its index in `gold_map`.
3) If no solution is found by the end of the loop, return an empty list (though the problem assumes there is exactly one solution).
⚠️ Common Mistakes
def find_treasure_indices(gold_amounts, target):
gold_map = {}
for i, amount in enumerate(gold_amounts):
complement = target - amount
if complement in gold_map:
return [gold_map[complement], i]
gold_map[amount] = i
return []