Two Sum
Easy
Given a list of numbers nums and an integer target, find the two numbers that add up to the target, and return their positions (indices).
You have a list like [2, 7, 11, 15] and target 9. Since 2 + 7 = 9, their positions are 0 and 1, so the answer is [0, 1]. Each problem has exactly one answer, and you cannot use the same number twice.
Reference: LeetCode #1 • Two Sum
Algorithm Visualization
Optimal Approach (One-Pass Hash Map)Look at 11 (index 1)
IN PROGRESSWe look at 11. To reach target 9, we need partner -2 (9 - 11 = -2). Have we seen -2 before? No. So we save { 11: index 1 } and move to the next number.
-2 not in map. Save key 11 with index 1: map.set(nums[i], i);Why is the Hash Map Solution Best?
How to think through the problem and discover the fast solution yourself step by step.
Brute Force
Test every possible pair one by one using two nested loops.
Why is it slow?
For 10,000 numbers, checking all pairs takes ~50 million checks. It is too slow!
What partner do we need?
For any number x, we know the exact partner we need: target - x.
Use a Notebook
Write each number down in a hash map notebook as you pass it. Looking inside takes 1 instant step!
One Single Pass
Walk through the list once. Check if the partner is in your notebook. If yes, you are done!
Optimal Approach (One-Pass Hash Map)
We walk through the list of numbers only once. Looking up or adding an item in a hash map happens in 1 quick step.
In the worst case, we save up to n numbers in our notebook until we find the match.
Example Test Cases
Simple examplesRules & Limits
Constraints- At least 2 numbers
The list will always have 2 or more numbers, up to 10,000 numbers (
2 ≤ nums.length ≤ 10⁴). - Numbers can be negative
Numbers can be positive, negative, or zero (
-10⁹ ≤ nums[i], target ≤ 10⁹). - Exactly one solution
You are guaranteed that exactly one valid pair exists.
- Cannot use the same number twice
You cannot use the element at the same index twice.
Important Things to Remember
Key Lessons
Instead of adding every pair, calculate what number you need: needed = target - current. Then check if you have already seen that partner!
Two loops take O(n²) time (slow). Storing seen numbers in a quick-lookup hash map takes a tiny bit of extra memory, but solves the problem in just 1 pass (fast O(n)).
Check your notebook before saving the current number. This guarantees you will never accidentally pair a number with itself!