Pair With Target Sum
Given a list of integers nums and an integer target, return the indices [i, j] with such that nums[i] + nums[j] == target.
If several pairs work, return the one with the smallest j, and among those the smallest i. Return [] if no pair exists.
Requirements
- Run in time using a hash map.
- Do not use the same element twice.
Constraints
-
nums[i],target
Examples
EXAMPLE WALKTHROUGHvalues 2 and 7
A guided view of the published example, not a trace of your code.
INPUT
[[2,7,11,15],9]TASKpair_with_target_sum()
EXPECTED OUTPUT
[0,1]Start with the input values shown in this example.
Example 1 of 3
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: values 2 and 7
Input: nums = [3,2,4], target = 6
Output: [1,2]
Explanation: pair is not at the start
Input: nums = [1,2], target = 7
Output: []
Explanation: no valid pair
Hint 1
As you scan left to right, what value would complete a pair with the current number?
Hint 2
Store each value's first index in a dictionary before moving on.