DSA Visualizer · 25 visualizationsTwo Sum
Two Sum
Find two indices whose values add up to the target. Instead of checking every pair, remember what you've already seen.
Start with an empty hash map. It will remember every number we've passed and where we saw it.
Problem
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.
You may assume each input has exactly one solution, and you may not use the same element twice.
Examples
nums[0] + nums[1] = 2 + 7 = 9
Constraints
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
- Only one valid answer exists.
Intuition
For each number x we need exactly one partner: target − x. Instead of searching the rest of the array for it, remember every number we have already passed in a hash map. Then 'have I seen my partner?' is a single lookup.
Brute force → Optimal
Try every pair with two nested loops and check whether it sums to the target.
One pass with a hash map from value to index. For each number, look up target − x before storing x.
Complexity
Edge cases
- Duplicate values, e.g. [3, 3] with target 6: look up before you store, so the element never pairs with itself.
- Negative numbers and zero: target − x can be negative; the map handles it the same way.
Common mistakes
- Storing x before looking up its partner, which lets an element pair with itself.
- Returning values instead of indices.