Two Sum
Indices of two array elements whose sum equals a target
Return the indices of the two numbers in nums that add up to target.
Examples
Example 1
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
2 + 7 = 9
Example 2
Input: nums = [3,2,4], target = 6 Output: [1,2]
Constraints
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i], target ≤ 10⁹
Additional Context
- Exactly one valid answer exists.
- Return the indices (0-based) in increasing order.
- Prefer O(n) solutions using auxiliary space rather than O(n²) brute force.
Hints
Show hint 1Hint 1
Use a hash map from value -> index while iterating.
Show hint 2Hint 2
As you scan, check if target - nums[i] exists in the map.
Follow-up questions
What an interviewer might ask once you have a working solution.
- What changes if multiple answers can exist?
- Can you solve it in-place?
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem