Two items for the budget
An interview classic – find two different positions in a price list that add up to exactly the given amount. One pass with a map instead of two nested loops.
A gift card is worth target and has to be spent to the cent on two different products. Prices are in the array nums (integers). Return the indices [i, j] such that i < j and nums[i] + nums[j] == target.
Task
- When several pairs match, the one with the smallest
jwins; for the samej, the smallesti. - An element cannot be used twice (two equal prices at different positions are fine).
- When there is no pair, return an empty array.
Signatures: twoSum(nums, target) (JS/TS), two_sum(nums, target) (Python), Solution.TwoSum (C#), Solution.twoSum (Java), TwoSum (Go).
Examples
nums | target | Result | Why |
|---|---|---|---|
[2, 7, 11, 15] | 9 | [0, 1] | 2 + 7 |
[1, 4, 2, 5] | 6 | [1, 2] | pairs (0, 3) and (1, 2) – (1, 2) has the smaller j |
[2, 2, 5, 4] | 6 | [0, 3] | for j = 3 the smallest i is 0 |
[5, 1] | 10 | [] | 5 cannot be used twice |
Constraints
0 ≤ nums.length ≤ 100,000; values andtargetfit in a 32-bitint, but the sum of two values may not (in C# and Java compute inlong).- Values may repeat.
Expected complexity
O(n) time, O(n) extra memory. An O(n²) solution will not fit in the time limit of the performance test.