Forward Deployed EngineeringCodingHash Maps

Two Sum: return indices of the two numbers that add to a target

Question 27 of 73 · Updated

On this page

Interview-ready answer#

I would use a hash map to solve Two Sum in expected O(n) time. For each number x at index j, I calculate its complement, target − x. If that complement already exists in a map of previously visited numbers to their indices, I return its stored index and j. Otherwise, I store x with its index and continue.

The important detail is that I check for the complement before inserting the current number. That prevents using the same array element twice and still handles duplicate values, such as [3, 3] with target 6.

A brute-force solution checks every distinct pair in O(n²) time and O(1) auxiliary space. The hash-map solution trades O(n) auxiliary space for expected O(n) time and preserves original indices without sorting.

1. Clarify the problem contract#

Given an array of integers nums and an integer target, return the original zero-based indices of two distinct elements whose values sum to target.

For example:

InputTargetValid output
[2, 7, 11, 15]9[0, 1]
[3, 2, 4]6[1, 2]
[3, 3]6[0, 1]
[-3, 4, 3, 90]0[0, 2]
[1, 2, 3]10None

The classic interview variant guarantees exactly one solution and allows the indices in any order. These implementations also support arrays with multiple valid pairs (return any one) and arrays with no solution (return None). Clarify the expected no-solution behavior with the interviewer; an API may instead use an empty list or raise a documented exception.

The answer contains indices, not the values themselves. Two equal values can be used if they occupy different positions. Do not mutate the input.

2. Brute-force solution#

A direct approach enumerates each unordered pair of different indices. For each i, start j at i + 1 to avoid both comparing an element with itself and checking the same pair twice.

PYTHON
def two_sum_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

For nums = [3, 2, 4] and target = 6:

ijSumDecision
013 + 2 = 5Continue
023 + 4 = 7Continue
122 + 4 = 6Return [1, 2]

There are n(n − 1)/2 distinct index pairs. If no pair exists, all are checked. The algorithm is correct because it visits every possible pair with i < j and returns only when the required equality holds.

Complexity: Worst-case time O(n²), best-case time O(1) when the first pair matches, auxiliary space O(1), excluding the constant-size output. This baseline is useful as a correctness oracle and for understanding why a more efficient search is desirable.

3. Optimal expected-time solution: one-pass hash map#

Rearrange the required equation:

nums[i] + nums[j] = target

nums[i] = target − nums[j]

When visiting nums[j], the only value we need to search for is target − nums[j]. A dictionary provides expected constant-time membership checks and updates under ordinary hashing assumptions.

PYTHON
def two_sum(nums, target): seen = {} for j, value in enumerate(nums): need = target - value if need in seen: return [seen[need], j] seen[value] = j return None

The map stores number → original index, not index → number. If the same number is encountered again without producing a match, its most recent index replaces the old index. That is valid when any solution is acceptable: every stored index is earlier than the current index. A different output-order requirement may need a different tie-breaking strategy.

Control flow#

Loading diagram…

Dry run#

Input: nums = [2, 7, 11, 15], target = 9.

jCurrent valueComplementMap before checkAction
027emptyStore 2 → 0
1722 → 0Return [0, 1]

There is no need to visit 11 or 15 after finding the pair.

Why duplicates work#

For nums = [3, 3] and target = 6, the first iteration looks for 3 in an empty map and stores 3 → 0. The second iteration finds 3 in the map and returns [0, 1]. With only one element [3], no pair is returned.

Checking after inserting the current value can incorrectly produce [0, 0] when target is twice that value. Checking before insertion ensures the returned indices are distinct.

4. Correctness proof#

Loop invariant: At the beginning of iteration j, the map contains every distinct value in the prefix nums[0:j], associated with some valid index strictly less than j, assuming the algorithm has not returned.

Initialization: Before iteration zero, the prefix and map are empty.

Maintenance: If the complement exists, its stored index i satisfies i < j and nums[i] = target − nums[j], so the returned pair is valid. Otherwise, storing nums[j] at index j preserves a valid representative for each distinct prefix value for the next iteration.

Completeness: Suppose any valid pair exists with indices i < j. If the algorithm has not already returned a valid pair before iteration j, the value nums[i] is present in the map by the invariant. It equals target − nums[j], so the algorithm returns a valid pair at or before that iteration. Consequently, returning None after the full scan implies that no valid pair exists.

This proof does not rely on the existence of a unique solution, sorted input, or positive integers.

5. Complexity and alternatives#

ApproachTimeAuxiliary spaceConsideration
Brute forceO(n²) worst caseO(1)No hashing or input mutation
One-pass hash mapO(n) expected/amortized under normal hashing assumptionsO(n)Retains original indices
Sort indexed pairs + two pointersO(n log n)O(n) for indexed copyPreserves original indices via explicit pairs
Two pointers on already sorted inputO(n)O(1)Requires sorted input

Hash-table membership and insertion have expected O(1) cost in standard interview analysis. Pathological collisions can degrade performance, so O(n) should not be described as an unconditional worst-case guarantee for Python dictionaries. These complexity bounds use the usual unit-cost model for fixed-size integer operations; arbitrary-precision arithmetic has additional bit complexity.

The hash-map approach is asymptotically optimal in expected time for arbitrary unsorted input under the usual model: without a guarantee permitting earlier termination, an algorithm may need to inspect all n values. A solution can depend on the last element.

If the input is already sorted, start with a pointer at either end. If the sum is too small, advance the left pointer; if too large, move the right pointer inward. For unsorted input, sorting just the values would lose the original indices. Sorting (value, original index) pairs preserves them but costs additional time and space.

6. Edge cases and common mistakes#

  • Empty array or a single element: return None under the stated extended contract.
  • Duplicate values: [3, 3] with target 6 returns distinct indices.
  • Negative values and zero: the complement equation is unchanged.
  • Multiple solutions: either algorithm can return a different valid pair; neither promises the lexicographically smallest pair.
  • Very large integers: Python integers support arbitrary precision, but fixed-width implementations in other languages may need wider arithmetic or overflow checks.
  • A complement at index zero: test membership with "need in seen" rather than the truthiness of seen.get(need), because zero is falsy.
  • Input mutation: avoid sorting the original array when the task requires original indices.
  • Returning values: [2, 7] is not the requested output for [2, 7, 11, 15] and target 9.

7. Tested implementation and verification#

Both exact Python implementations above were executed locally with Python 3.13.5. An independent oracle generated the complete set of valid index pairs using combinations of distinct indices.

42,972 input cases passed for each implementation (85,944 validated results in total). This consists of 42,966 exhaustive cases over arrays of length zero through five, values from −2 through 2 and targets from −5 through 5, plus six explicit regression cases. The regression cases included the standard example, equal elements, repeated zeros, negative numbers, integers of magnitude 10^100, and a single element without a solution.

For each exhaustive case, a returned pair had to belong to the independently computed valid-pair set, and None was accepted only when that set was empty. The implementations were not required to choose the same pair when several solutions existed.

These checks establish correctness on the tested inputs; they are not a production performance benchmark.

8. Interviewer follow-ups#

Can we use a set instead of a dictionary? A set is enough to determine whether a pair of values exists. Returning original indices requires storing an index or performing another lookup.

What if the input is a stream? The same one-pass strategy can consume values as they arrive and return indices once a match appears. It may still retain O(n) distinct values; a bounded-memory variant needs additional assumptions or external storage.

What if all valid index pairs are required? Keep a list of earlier indices per value. At each element, emit one pair for every stored complement index, then append the current index. Expected time is O(n + p) and auxiliary space O(n), excluding p output pairs. The output itself can be quadratic, such as when every number is zero and the target is zero.

What if only the number of valid pairs is required? Store earlier-value frequencies rather than index lists. For each value, add the current frequency of its complement to the count, then increment its own frequency. This counts each unordered pair once in expected O(n) time.

Why does sorting not automatically solve the original problem in linear time? The two-pointer scan is linear after sorting, but sorting arbitrary unsorted input normally takes O(n log n) comparison time and original indices must be retained.

How would this relate to FDE work? The complement lookup illustrates replacing a repeated search with an index or hash join. In an integration that matches records using a deterministic key, similar indexing can reduce repeated scans. Real record matching also requires handling duplicates, provenance, authorization and domain-specific matching semantics; Two Sum alone is not a complete reconciliation design.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models