Easy · Arrays and hashing · Python | Prerequisites: loops, lists and dictionaries. Learn to turn repeated searching into a single pass.
Imagine matching two purchases to a fixed budget. You know the price of one item; the missing price is determined immediately. The challenge is locating that second item without scanning the entire list again. Two Sum is a foundational exercise in recognizing when a dictionary can replace a nested loop.
Find the complement before storing the current value.
Problem statement and constraints
Given an integer list nums and an integer target, return two distinct zero-based indices whose values sum to target. For this tutorial, allow any valid pair and return None when no pair exists. The standard interview variant guarantees exactly one answer. Assume 2 to 10,000 elements and integer values and target between −1 billion and 1 billion; our implementations also handle empty lists.
Examples: [2,7,11,15], target 9 → [0,1]; [3,3], target 6 → [0,1]; [-4,8,1], target 4 → [0,1]; [1,2], target 9 → None. The output is indices, not values.
Progressive hints
Hint 1: Start by checking every pair of distinct positions. Hint 2: For a fixed value x, what must the other value be? Hint 3: Can you remember values already visited and their original positions? Hint 4: Decide whether to search the dictionary before or after inserting the current value.
Brute force: enumerate pairs
The simplest correct approach fixes a first index and checks every later index. Starting the inner loop at i+1 avoids self-pairs and duplicate work. Return immediately on a match; otherwise finish both loops. This is a useful reference implementation because it is easy to reason about.
def brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return None
In the worst case there are n(n−1)/2 comparisons. Time is O(n²) and auxiliary space O(1), excluding the constant-sized answer. At n=10,000 this can mean 49,995,000 pair checks. The bottleneck is repeatedly searching for a complement.
Derive the optimized approach
Rearrange x+y=target into y=target−x. Rather than search the remaining list, ask whether a suitable value has already appeared. A dictionary maps each earlier value to its index. If the complement exists, return that earlier index and the current index. Otherwise record the current value. This preserves original positions and does not require sorting.
CREATE empty dictionary seen
FOR each index i and value x:
need = target – x
IF need exists in seen:
RETURN [seen[need], i]
STORE seen[x] = i
RETURN None
Optimized Python implementation
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
complement = target – x
if complement in seen:
return [seen[complement], i]
seen[x] = i
return None
Step-by-step dry run
Use nums=[4,1,9,6], target=10. The first element needs 6, which is not yet stored. The second needs 9, also absent. The third needs 1, which is already stored at index 1. Return [1,2]. The final element is never visited.
IndexValueNeedSeen before lookupAction046EmptyStore 4 → 01194 → 0Store 1 → 12914 → 0, 1 → 1Return [1,2]
Why the algorithm is correct
Invariant: immediately before processing index i, the dictionary contains an earlier index for every distinct value in nums[0:i]. Initially the prefix is empty. If the complement is found, its index j is strictly less than i, and nums[j]+nums[i]=target. If not found, inserting x maintains the invariant for the next iteration. For any valid pair j<k, either the algorithm already returned a valid pair, or when k is reached the value at j is present. Therefore a valid pair cannot be missed. Overwriting a duplicate value preserves at least one earlier index, which is sufficient when any pair is accepted.
Complexity comparison
ApproachTimeAuxiliary spaceBrute forceO(n²) worst caseO(1)Hash mapO(n) expectedO(n)
Dictionary operations are expected constant time under ordinary hashing assumptions; pathological collisions can degrade performance. The hash map trades memory for speed. Both algorithms can finish early. Sorting with two pointers is another option, but preserving original indices requires additional bookkeeping.
Edge cases and validation
Test equal values [3,3], negative values [-4,8,1], zeroes [0,0], no answer [1,2], an empty list, and multiple valid pairs [1,2,3,4] with target 5. For multiple answers, validate the returned indices rather than expecting the same pair from both algorithms. Both implementations were tested against duplicates, negative values, and no-solution cases.
Common mistakes
Do not insert the current value before checking its complement: with [3,4] and target 6, that could incorrectly return [0,0]. Do not return the complement itself instead of its index. Do not assume positive values or sort the input without preserving indices. Avoid claiming constant auxiliary space for a dictionary that can grow with the input.
Interview questions and answers
Why use a dictionary rather than a set?
A set tells you whether a value exists; a dictionary also retrieves its original index.
Can we use two pointers?
Yes, if the input is sorted or we sort value-index pairs first. Sorting generally costs O(n log n).
What if all pairs are required?
Store lists of earlier indices and emit every matching pair. Output size can itself be quadratic.
How would this work with a stream?
Keep the dictionary across incoming values and stop when a complement arrives. Memory can grow without bound unless the problem imposes a window.
Why check before insertion?
It guarantees distinct indices, even when the complement equals the current value.
Related practice
Try Two Sum II (sorted input), 3Sum, counting pairs with a given sum, and Subarray Sum Equals K. Each changes a constraint or the required output; do not blindly reuse the same dictionary logic.
Practice: Two Sum. Continue with our sliding window tutorial to see another way to use remembered state.
Quick revision
Recognize the pattern: repeated complement lookup. Derive target−x, check the dictionary, then insert the current index. State the invariant and explain expected O(n) time and O(n) space. Practice writing both implementations without notes, then test duplicates and no-answer cases before moving on.
No Responses