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).

4 variations · 4 problems · 3 with animated walkthroughs

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

Two Sum
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[]{};
}

The variations

  1. 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.

  2. 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.

  3. 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.

    Worked example 3Sum Medium ▶ Watch the walkthrough
  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

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.
Next: Moore's voting: the majority in O(1) space →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.