Two Sum
Easy · Arrays & Hashing · Array · Hash Table
Problem
You are given an array of integers nums and an integer target.
Find the two numbers in the array that add up to target, and return their positions — not the numbers themselves.
Three things the problem guarantees, which shape every solution:
- Exactly one pair works. You never have to choose between answers, and you never have to handle "no answer".
- You may not reuse a single element. The two positions must be different, so an element cannot pair with itself.
- Order does not matter. [0, 1] and [1, 0] are both accepted.
Examples
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
nums[0] + nums[1] == 9.
Input: nums = [3,2,4], target = 6 Output: [1,2]
Input: nums = [3,3], target = 6 Output: [0,1]
The same value may appear twice at different indices.
Constraints
- 2 <= len(nums) <= 10^4
- -10^9 <= nums[i] <= 10^9
- Exactly one valid answer exists
Approaches
- Brute force — check every pair — time O(n²), space O(1)
Follow-up
Can you do better than checking every pair, i.e. faster than O(n²) time?
Related problems
Start free on Cariara · Coding problems · System design studio