Fill the blank
Fill the blank so a gift is never paired with itself.
def gift_pair(prices: list[int], budget: int) -> list[int]:
first_at: dict[int, int] = {}
for j, p in enumerate(prices):
____
if p not in first_at:
first_at[p] = j
return []
print(gift_pair([3, 4, 3], 6))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A if budget - p in first_at: return [first_at[budget - p], j]
Right: the lookup runs before the current price is stored, so index j can only pair with an earlier index.
With [3, 4, 3] and budget 6 the answer must be [0, 2]: the two different gifts priced 3, never gift 0 with itself.
Why not the others?
- B first_at[p] = j. Storing first means the lookup can find the same gift when budget is twice its price.
- C return [j, j]. That returns the same gift twice and ignores the budget.