beginner7 min read·Updated September 17, 2026

Two Sum with a Hash Map Explained: Tracing [3, 2, 4] and [3, 3]

Master the Two Sum hash map pattern with a complete walkthrough of [3, 2, 4] and [3, 3]. Learn the mental model, complement logic, and O(n) time complexity.

By Learnisim AI·Published September 17, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • Basic arrays and indexing
  • Basic hash map or dictionary operations
Two Sum: Single-Pass Hash Map vs. Brute Force (nums = [3, 2, 4], target = 6) 1. Brute Force O(n²) & Edge Case [3, 3] Nested loops check redundant pairs and risk self-pairing. 3 i=0 2 i=1 4 i=2 [3, 3] target 6 trap: Naive loop pairs index 0 with itself => returns [0, 0]! Checks (3+2), (3+4), (2+4). Slow on large arrays. 2. Single-Pass Hash Map Model O(n) Check complement (target - num) in map before storing. complement = target - num seen = { num : index } Step 0: { 3: 0 } Step 1: { 3:0, 2:1 } Step 2: 6-4=2 found! Returns [1, 2] for i, num in enumerate(nums): comp = target - num if comp in seen: return [seen[comp], i] seen[num] = i 3. Step-by-Step Execution on nums = [3, 2, 4], target = 6 Watch how the hash map captures previous values instantly without nested loops. Step i=0 num = 3 • Complement: 6 - 3 = 3 • Is 3 in seen? No ({}) • Action: Store seen[3] = 0 seen = {3: 0} Step i=1 num = 2 • Complement: 6 - 2 = 4 • Is 4 in seen? No ({3:0}) • Action: Store seen[2] = 1 seen = {3:0, 2:1} Step i=2 num = 4 • Complement: 6 - 4 = 2 • Is 2 in seen? YES! (idx 1) • Return [seen[2], 2] ⇒ Result: [1, 2]
Two sum on [3, 2, 4] target 6 — and [3, 3] target 6 overview diagram
Why

Why Nested Loops Fail Us on [3, 2, 4]

Imagine you are handed the array and a target sum of 6. You need to find two distinct indices whose values add up to 6. If you try the most obvious approach—checking every possible pair with nested loops—you look at , then , and finally . On a tiny array, that feels trivial. But what happens when your array grows to 100,000 numbers? Your computer starts burning CPU cycles recalculating sums it has already seen, scaling quadratically at time complexity. Worse yet, consider what happens on with target 6: a naive loop might accidentally pair index 0 with itself, returning , which violates the rule that you must use distinct indices. We need a way to look back in constant time at what numbers we have already passed, without rescanning the entire array from scratch.
python
nums = [3, 2, 4], target = 6
# Why does a nested loop check redundant pairs?
# How can we avoid looking at (2, 3) after already checking (3, 2)?
Why Nested Loops Fail Us on [3, 2, 4] (Target: 6) Naive Nested Loops: O(n²) Scalability Trap nums = 3 idx 0 2 idx 1 4 idx 2 Check (3, 2): sum = 5 != 6 Check (3, 4): sum = 7 != 6 Redundant Found at end! The [3, 3] Self-Pair Trap (Target 6): Naive loop compares index 0 with itself! Accidentally returns [0, 0] (violates rule) Requires extra guards against self-matching. 100k elements = 5,000,000,000 checks Quadratic slowdown & duplicate bugs Hash Map Solution: O(n) Single Pass "What do I need to reach target 6?" 1 See 3. Need: 6 - 3 = 3. Map is empty. Store {3: idx 0} 2 See 2. Need: 6 - 2 = 4. 4 not in map. Store {2: idx 1} 3 See 4. Need: 6 - 4 = 2. 2 IS in map! Return [idx(2), idx 2] Map: {3: 0, 2: 1} Constant time O(1) lookups per element Solves [3, 3] naturally (checks map BEFORE storing)
Why Nested Loops Fail Us on [3, 2, 4] diagram
Model

The Single-Pass Hash Map Model on [3, 2, 4] Target 6

Building on our motivation from the brute-force failure, how can we solve nums = [3, 2, 4] with target = 6 in a single left-to-right pass? Instead of asking a second loop to scan the rest of the array, we ask a hash map to remember what we have already seen behind us. As we visit each number at index , we immediately calculate its complement: . If that complement is already sitting inside our hash map, we have our two indices instantly. If it is not there yet, we store alongside its index and move one step forward.
Single-Pass Hash Map Model: Two Sum on [3, 2, 4], Target = 6 For each x at index i, check if (target - x) is in map. If not, store x and advance. Step 1: i = 0, x = 3 3 idx 0 2 idx 1 4 idx 2 Comp: 6 - 3 = 3 Map is empty! Store: {3: 0} Step 2: i = 1, x = 2 3 idx 0 2 idx 1 4 idx 2 Comp: 6 - 2 = 4 4 not in map Store: {2: 1} Step 3: i = 2, x = 4 4 idx 2 Comp: 6-4=2 Found 2! Ans: [0, 2] Hash Map Dynamic State (Key : Index) After Step 1 (i=0): { 3 : 0 } After Step 2 (i=1): { 3:0, 2:1 } After Step 3 (i=2): Match found! O(1) lookups ensure total runtime is strictly O(n). Edge Case Walkthrough: nums = [3, 3], target = 6 i = 0, x = 3: Comp: 6 - 3 = 3. Not in map. Insert {3: 0} BEFORE checking? No, check first! i = 1, x = 3: Comp: 6 - 3 = 3. Found in map at idx 0! Return [0, 1] instantly without overwriting. Rule: Always check complement *before* adding current x. This prevents self-pairing bugs on duplicate elements.
The Single-Pass Hash Map Model on [3, 2, 4] Target 6 diagram
Syntax

Syntax and APIs for Two Sum on [3, 2, 4]

To implement our single-pass model on nums = [3, 2, 4] and target = 6, we need a concrete data structure. In Python, a dictionary acts as our hash map, mapping each number to its index. As we loop through the array with enumerate(nums), we check if the complement target - num already exists in our dictionary before we store the current number. If it exists, we immediately return the stored index and our current index. If it does not, we record num: i in the dictionary and move forward.
python
def twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        # Complete the syntax to check the hash map and store the current number
Worked example

Walking Through Two Sum on [3, 2, 4] Target 6 Step-by-Step

Let's trace our algorithm completely on the locked example: nums = [3, 2, 4] with target = 6. We maintain an empty hash map seen to store { value: index } as we move from left to right.
Given: nums = [3, 2, 4], target = 6
Steps:
1. Index 0: Element is 3. Complement is . We check if 3 is in our seen map. It is not (map is empty). We store our current value and index: seen[3] = 0. Map state: {3: 0}.
2. Index 1: Element is 2. Complement is . We check if 4 is in seen. It is not (seen only has key 3). We store: seen[2] = 1. Map state: {3: 0, 2: 1}.
3. Index 2: Element is 4. Complement is . We check if 2 is in seen. Match found! Key 2 exists at index 1. We immediately return [seen[2], 2], which evaluates to [1, 2].
Result: Returns [1, 2]. This correctly references values nums[1] = 2 and nums[2] = 4, which sum to .
python
def two_sum_trace(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

# Trace for [3, 2, 4], target 6
print(two_sum_trace([3, 2, 4], 6))
Walking Through Two Sum: nums = [3, 2, 4], target = 6 Trace across 3 iterations ending with Match Found at Index 2 nums array: i = 0 val: 3 i = 1 val: 2 i = 2 (MATCH!) val: 4 Iteration 1: Index 0 • Element: 3 • Complement: 6 - 3 = 3 Is 3 in seen? No (empty) Store seen[3] = 0 Map state: {3: 0} Iteration 2: Index 1 • Element: 2 • Complement: 6 - 2 = 4 Is 4 in seen? No Store seen[2] = 1 Map state: {3:0, 2:1} Iteration 3: Index 2 • Element: 4 • Complement: 6 - 4 = 2 Is 2 in seen? MATCH! Return [seen[2], 2] Result: [1, 2] (Sums to 6)
Walking Through Two Sum on [3, 2, 4] Target 6 Step-by-Step diagram
Practice

Practice: Predict the Hash Map State and Return Indices for [3, 3] Target 6

Now it is your turn to apply the single-pass hash map algorithm we traced for [3, 2, 4] to our second working example: nums = [3, 3], target = 6. Recall that our core rule was checking the complement before inserting the current element to prevent pairing an element with itself. Work through the iterations at index 0 and index 1, tracking what the hash map contains at each step.
javascript
function twoSum(nums, target) {
    const map = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        // TODO: Check if complement exists in map, else store nums[i]
    }
}
Apply

Applying the Complement Pattern to Find Three Sum Indices

Now that you have mastered the single-pass hash map pattern on our working examples [3, 2, 4] target 6 and [3, 3] target 6, it is time to transfer this exact mental model to a neighboring problem: finding pairs in a stream, or adapting the logic when requirements shift. Consider how the core principle—checking for target - x in time before inserting x into memory—prevents self-pairing and eliminates redundant nested loops. When you encounter variations like finding if any two numbers sum to a target in a sorted versus unsorted array, or adapting the hash map to store frequencies instead of indices, the foundational insight remains identical. You are always trading space for time by caching past states so future lookups happen instantly.
python
def has_two_sum(nums, target):
    # Apply the single-pass hash map pattern here
    pass

FAQ

How does the hash map approach solve Two Sum in O(n) time?
Instead of using nested loops to check every possible pair (which takes O(n²) time), we store each number and its index in a hash map as we iterate. For every number, we instantly check if its complement (target - current number) already exists in the map.
Why does the trace on [3, 3] with target 6 return [0, 1] instead of [0, 0]?
By checking for the complement before inserting the current number into the hash map, we prevent an element from being paired with itself. When the second '3' is evaluated, the first '3' is already in the map, correctly yielding indices [0, 1].
What happens if there are multiple valid solutions for Two Sum?
Most standard Two Sum problems guarantee that exactly one solution exists, and you can return the indices in any order. The single-pass hash map approach will naturally return the first valid pair it completes.
What is the space complexity of the Two Sum hash map solution?
The space complexity is O(n) in the worst case, because we store up to n elements and their indices in the hash map if the valid pair is found at the very end of the array.

Keep learning