The Runtime Theory
easyleetcode#hash-map#array

Two Sum

Find two array indices that add up to a target using a hash map to store complements in a single pass — the classic array and hash map interview problem.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[2,7,11,15], 9

out[0,1]

in[3,2,4], 6

out[1,2]

in[3,3], 6

out[0,1]

The machine must return the indices of two numbers that add up to a target, and exactly one solution is guaranteed. The naive approach checks every pair, which is O(n²). The insight: you never need to look ahead. Walking left to right, each element asks "have I already seen the complement target - num?" A hash map answers that in O(1).

python
def two_sum(nums, target):
    seen = {}  # value -> index
    for i, num in enumerate(nums):
        comp = target - num
        if comp in seen:
            return [seen[comp], i]
        seen[num] = i

Steps: (1) iterate once, (2) check whether the complement is in the map, (3) if found, return [stored_index, i]; otherwise record num -> i and keep going.

Time is O(n): every lookup and insert is O(1) amortized, over n elements. Space is O(n) in the worst case, when the answer sits at the end of the array.

Trickiest edge case: duplicates like [3, 3] with target 6, and the self-pair trap when target == 2 * num. Because each value is stored only after its own lookup, an element can never pair with itself — check-then-store is what makes [3,3] return [0,1].

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.