Two Sum
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.
Understand the problem
- An index is a position in the array, counting from
0. In[2, 7, 11, 15], the value2is at index0and7is at index1. - You return the positions, not the numbers themselves.
- There is always exactly one correct pair, so you never need to handle "no answer".
- You can't use the same position twice: with
target = 4, a single2doesn't count as2 + 2. - The two indices can be returned in any order.
Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]nums[0] + nums[1] is 2 + 7, which is 9.
Example 2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]2 + 4 = 6. Note that 3 + 3 would also be 6, but there's only one 3, and we can't use it twice.
Example 3
Input: nums = [3, 3], target = 6
Output: [0, 1]Two different positions that happen to hold the same value are fine.
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i], target <= 10^9- Exactly one valid answer exists.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
For every number, work out the partner it needs (target - number) and check whether you've already seen that partner.
The naive approach (and why it's slow)
Try every pair:
nums = [2, 7, 11, 15], target = 9
2+7 ✅ (and if not: 2+11, 2+15, 7+11, 7+15, 11+15)With n numbers there are about n × n / 2 pairs, so this is O(n²). For 10,000 numbers that's 50 million additions.
The key insight
When you're standing on a number, you know exactly which number would complete the pair: complement = target - number. So the question changes from "which pair works?" to "have I seen this specific value before?", and a hash map answers that in one step.
We need to return positions, so the map stores value → index.
Step by step
nums = [3, 2, 4], target = 6:
| Index | Number | Complement (6 - number) | In the map? | What we do | Map afterwards |
|---|---|---|---|---|---|
| 0 | 3 | 3 | No (empty) | store 3 → 0 | {3: 0} |
| 1 | 2 | 4 | No | store 2 → 1 | {3: 0, 2: 1} |
| 2 | 4 | 2 | Yes, at 1 | return [1, 2] ✅ |
Look at step 0: the complement of 3 is 3 itself. Because we check the map before storing the current number, the 3 doesn't find itself, which is exactly right (we can't use one element twice).
And for nums = [3, 3], the second 3 does find the first one in the map, and we correctly return [0, 1].
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One pass over the array, and each map lookup takes one step.
- Memory: O(n). In the worst case we store every number before finding the pair.
Common mistakes
- Storing before checking. Then a number can pair with itself: with
nums = [3, 2, 4]andtarget = 6, the3would find its own entry and return[0, 0]. - Using a set instead of a map. A set can tell you the complement exists, but not where it is, and the answer must be indices.
- Filling the whole map first, then searching. It can work, but you then need extra care to avoid matching an element with itself. Checking as you go avoids the problem entirely.
Going deeper
Why not sort and use two pointers? Sorting loses the original positions, so you'd have to sort (value, index) pairs. It works in O(n log n), but the hash map is simpler and faster here. Two pointers come back in 3Sum, where sorting really pays off.
Reference solution
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
export default function twoSum(nums, target) {
// value -> the index where we saw it
const indexOf = new Map()
for (let i = 0; i < nums.length; i++) {
// The one value that would complete the pair with nums[i].
const complement = target - nums[i]
// Did we already walk past it?
if (indexOf.has(complement)) return [indexOf.get(complement), i]
// Store AFTER checking, so a number can't pair with itself.
indexOf.set(nums[i], i)
}
// The problem guarantees an answer, so we never get here.
return []
}export default function twoSum(nums: number[], target: number): number[] {
// value -> the index where we saw it
const indexOf = new Map<number, number>()
for (let i = 0; i < nums.length; i++) {
// The one value that would complete the pair with nums[i].
const complement = target - nums[i]
// Did we already walk past it?
const j = indexOf.get(complement)
if (j !== undefined) return [j, i]
// Store AFTER checking, so a number can't pair with itself.
indexOf.set(nums[i], i)
}
// The problem guarantees an answer, so we never get here.
return []
}def two_sum(nums: list[int], target: int) -> list[int]:
# value -> the index where we saw it
index_of = {}
for i, num in enumerate(nums):
# The one value that would complete the pair with num.
complement = target - num
# Did we already walk past it?
if complement in index_of:
return [index_of[complement], i]
# Store AFTER checking, so a number can't pair with itself.
index_of[num] = i
# The problem guarantees an answer, so we never get here.
return []