Somewhere in nums there are two numbers that add up to target. Find them and return their positions, counting from 0, with the smaller position first. The same position cannot be used twice.
Example 1
Input
nums = [8, 3, 12, 5], target = 17
Output
[2, 3]
Explanation
nums[2] + nums[3] is 12 + 5, which is 17. No other pair adds up to 17.
Example 2
Input
nums = [6, 1, 9, 6], target = 12
Output
[0, 3]
Explanation
6 + 6 is 12. There are two 6s, at positions 0 and 3, so they can be paired. A single 6 could not be paired with itself.
Constraints:
2 <= nums.length <= 10^5
-10^9 <= nums[i], target <= 10^9
exactly one pair of positions adds up to target
Follow-up: checking every pair takes O(n^2). Can you find the answer in O(n)?
Tab indents. Press Esc, then Tab to leave the editor.
Ctrl or ⌘ + Enter runs the tests.
Run your code to see every test here. Nothing is submitted or recorded.