Two Sum
Easy · Arrays & Hashing
Given an array of integers and a target integer, find the indices of the two numbers in the array that add up exactly to the target. Each input is guaranteed to have exactly one valid pair of indices, and you may not use the same element twice. Return the two indices in any order.
Examples
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Why: nums[0] + nums[1] == 9, so we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints
2 <= nums.length <= 10^4, -10^9 <= nums[i] <= 10^9, -10^9 <= target <= 10^9, exactly one valid answer exists
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Two Sum. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.