Two Sum

Find two numbers that add up to a target.

Pattern

Hash Map Lookup

This problem follows the Hash Map Lookup pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Store complements in a hash map. For each num, check if target - num exists.

Key Insight

Instead of searching for a pair, search for the complement of each number — this turns an O(n²) nested loop into a single O(n) pass.

Step-by-step

  1. 1Create an empty hash map (value -> index)
  2. 2For each number, calculate complement = target - num
  3. 3If complement exists in the map, return [map[complement], currentIndex]
  4. 4Otherwise, store the current number and its index in the map
  5. 5Continue until a pair is found

Pseudocode

map = {}
for i, num in enumerate(nums):
    complement = target - num
    if complement in map:
        return [map[complement], i]
    map[num] = i
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Arrays & Hashing Problems

Master this pattern with YeetCode

Practice Two Sum and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.

Practice this problem