easyHash maps and sets target 15 min
Two sum
You get a list of integers nums and an integer target. Exactly one pair of different positions holds two numbers that add up to target. Return those two positions as a list [i, j] with i < j.
A position can be used only once: if target is 8 and nums holds a single 4, then 4 + 4 is not an answer.
Example 1
Input
nums = [2, 7, 11, 15], target = 9Output[0, 1]nums[0] + nums[1] is 2 + 7 = 9.
Example 2
Input
nums = [3, 2, 4], target = 6Output[1, 2]2 + 4 = 6. Using the 3 twice would also make 6, but it sits at only one position.
Example 3
Input
nums = [3, 3], target = 6Output[0, 1]Two different positions can hold equal values.
Constraints
2 ≤ len(nums) ≤ 105
-109 ≤ nums[i], target ≤ 109
Exactly one valid pair exists.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.