Arrays and Hashing Hash map lookups
58. Two Sum
You are given an array of integers nums and an integer target. Exactly one pair of elements in nums
adds up to target. Return the indexes of those two elements as [i, j], with the smaller index first.
The two elements must sit at different positions. They may hold the same value. Indexes start at 0.
Example 1
Input: nums = [4, 11, -2, 7, 16], target = 14
[2,4]Explanation: −2 + 16 = 14, and −2 is at index 2 and 16 at index 4. The 7 at index 3 would need a second 7, and an element cannot be paired with itself.
Example 2
Input: nums = [3, 8, 3], target = 6
[0,2]Explanation: The two 3s add up to 6. They hold the same value but sit at different positions, so they count.
Example 3
Input: nums = [-6, -14, 25, -8], target = -20
[0,1]Explanation: −6 + (−14) = −20. The target can be negative, and the pair can be the first two elements.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
2 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109-2·109 ≤ target ≤ 2·109- Exactly one pair of indexes
i < jhasnums[i] + nums[j] = target.
Clarifying questions
What you would ask an interviewer before writing any code.