Arrays & Hashing · Pattern 1 of 26
Two Sum: find pairs with a hash map
For each number, the partner you need is target - x. Keep every number you have passed in a hash map and ask whether the partner is already there: one pass, O(n).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Two (or three) values that add up to a target
- Count pairs whose sum has some property
- The array is not sorted and you may not sort it
The template
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) return new int[]{seen.get(need), i};
seen.put(nums[i], i); // add after checking: no self-pairs
}
return new int[]{};
} def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i # add after checking: no self-pairs
return [] vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> seen; // value -> index
for (int i = 0; i < (int)nums.size(); i++) {
int need = target - nums[i];
if (seen.count(need)) return {seen[need], i};
seen[nums[i]] = i; // add after checking: no self-pairs
}
return {};
} function twoSum(nums, target) {
const seen = new Map(); // value -> index
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i); // add after checking: no self-pairs
}
return [];
} The variations
-
1Complement in a hash map
Store each value with its index; for every new value look up
target - x. Return as soon as you find it. -
2Count pairs instead of finding one
Keep counts in the map. For every new value, add how many earlier values complete it. With "sum is a power of two", try each power as the target.
-
3Three numbers: sort, fix one, two pointers
Sort, fix
nums[i], then find pairs summing to-nums[i]with two pointers on the rest. Skip equal values to avoid duplicate triplets. -
4More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Adding the current number before checking, which pairs an element with itself.
- Using two nested loops: O(n²) is the answer interviewers want you to improve.
- For 3Sum, skipping duplicates only for the first number and returning repeated triplets.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.