817. Two sum: find two prompts that exactly fill a token budget
Why it matters Two Sum is the most asked warm-up coding question, and the hash-map trick reappears in dedup and join problems.
This is the classic Two Sum interview problem in an LLM setting. You have the token counts of many prompts and want two different prompts that together use exactly the remaining context budget.
Write two_sum(counts, target). Return the pair of indices [i, j] with i < j and counts[i] + counts[j] == target that has the smallest j, and among those the smallest i. Return [] if no pair exists. Aim for O(n) with a dictionary instead of checking every pair.
def two_sum(counts, target)Example 1
Input: two_sum([300, 1200, 500, 700], 1200)
Output: [2, 3]
Example 2
Input: counts = [3, 3], target = 6
Output: [0, 1]
Example 3
Input: counts = [1, 2, 3], target = 100
Output: []
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 6 tests to be accepted.
Hint 1
For each element, what value would complete the pair?
Hint 2
Store each value's first index in a dict as you go, and check the dict before inserting the current value.
Common mistakes
- Checking every pair, which is O(n^2) and too slow for 200,000 items.
- Inserting the current value before checking, which pairs an element with itself.
Understand the idea
Walk the list once. For each value, the partner you need is target - value. A dictionary of values seen so far (keeping the first index of each) answers whether that partner appeared earlier in O(1).
counts [300, 1200, 500, 700], target 1200. At index 3 (700) we need 500, seen at index 2, so the answer is [2, 3].
if target - c in seen: return [seen[target - c], j]; else remember c