easyArrayHash TableArrays & Hashing

Two Sum

easyTime: O(n)Space: O(n)

The shape of the problem

Given an unsorted array and a target, return the indices of two elements that sum to the target. Exactly one solution is guaranteed.

Signals to notice

find a paircomplement lookupunsorted input

Brute force first

Check every pair: two nested loops, O(n²). Correct but throws away everything you have already seen.

The key insight

For any pair `(a, b)` with `a+b == target`, if you scan left-to-right, one of them is always the earlier-seen element. A map of "value → index" lets the later element find its partner in O(1).

Trace it on nums=[2,7,11,15], target=9

i=0 v=2   need 9-2=7   7 in map? no    → store {2:0}
i=1 v=7   need 9-7=2   2 in map? YES(0) → return [0,1]

What must stay true

The map always holds exactly `{ v -> earliest index of v }` for every v in `nums[0..i)`. No solution has been missed because every pair is tried at the moment of the second element.

Shape of the loop

seen = {}
for i, v in enumerate(nums):
  if target - v in seen:
    return [seen[target - v], i]
  seen[v] = i

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Storing the element in the map BEFORE checking for its complement. On input `[3, 3]` with target 6 and a single-entry map, that double-stores index 0 and loses the answer.

Arrays & Hashing Pattern