Example 1
- Input
- nums = [2, 7, 11, 15], target = 9
- Output
- [0, 1]
Because nums[0] + nums[1] == 9, we return [0, 1].
Given an integer array and a target value, return the indices of the two numbers that add up to the target. Exactly one valid pair exists and the same element cannot be used twice.
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.
You may assume that each input has exactly one valid solution, and you may not use the same element twice. You can return the answer in any order.
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9Because nums[0] + nums[1] == 9, we return [0, 1].
The first value 3 would need another 3, which is absent. Values 2 and 4 add to 6 at indices 1 and 2, so the answer is [1, 2].
The two 3 values occupy different positions. Neither index can be reused, but indices 0 and 1 together sum to 6.
For each number, subtract it from the target to find the only partner value that can complete the pair. In [2, 7, 11, 15] with target 9, the partner of 2 is 7. A map remembers each earlier value and its index; when 7 arrives, its partner 2 is already stored. Checking before storing keeps the two positions distinct, even when the values are equal.
Reveal Brute Force: intuition, complexity, and code
10^4.target minus that value.[3, 3] with target 6 need the lookup-before-insert order so one 3 does not pair with itself.target is twice its value.0 instead of i + 1, which rechecks pairs and compares each element with itself.When each element seeks a fixed partner value, remembering visited elements in a hash map turns a quadratic pair search into one linear scan.