Blueprints · Hash Map

Hash Map: Two Sum on an Unsorted Array, From O(n²) to One Pass

One problem, three stages: make it work, make it fast, make it lean. Step through each stage in the visualizer, then run all three on a big input in the benchmark and watch the brute force overheat.

The real-world version

An expense system flags pairs of transactions that together hit an approval limit exactly, a classic way to split a purchase and dodge sign-off. Transactions arrive in no particular order, and the answer must point back to the original rows.

The problem

Given an unsorted array nums and an integer target, return the indices of the two numbers that add up to target. Each input has at most one answer.

nums = [7, 2, 9, 4, 11, 5], target = 15  →  (3, 4)   # 4 + 11

X-ray: watch it run

Benchmark: will the forge overheat?

Run all three stages on a large input in your browser and compare the work each one does.

In the interview

Mention the trade-off: the hash map buys O(n) time with O(n) memory. If the interviewer then says "the input is sorted", switch to two pointers for O(1) space.