Two Sum

easy

Find two numbers that add up to target using hash map

Two Sum

Key Insight

Use hash map to store complements. For each num, check if (target - num) exists.

Step 1Setup
Find two numbers summing to 9
Array
2
0
7
1
11
2
15
3
HashMap
Empty

Create empty hash map to store {value: index}. Target = 9.

1 / 4

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Two Sum

Use hash map to store complements. For each num, check if (target - num) exists.

  1. Setup

    Create empty hash map to store {value: index}. Target = 9.

  2. Check First Element

    num=2. Complement = 9-2 = 7. Not in map. Store {2: 0}.

  3. Check Second Element

    num=7. Complement = 9-7 = 2. Found at index 0!

  4. Result

    Return indices [0, 1]. nums[0] + nums[1] = 2 + 7 = 9.