LC 1
LeetCode 1 · Easy

Two Sum

Given an array and a target, return the indices of the two numbers that add up to the target.

Hash map → · Very high frequency · Solve on LeetCode →

Try it

Step through the core mechanic. The simulator below runs the hash map shape this problem is built on.

Interactive · Two Sum (LC 1) complement-lookup with a hash map; check before insert
array
0
3
1
8
2
2
3
7
4
11
5
4
6
9
seen map (value → index)
empty
start: seen-map is empty
step 1 / 4
Why "check, then insert". Inserting first would let an array like [3, 3] with target 6 match a single element with itself. Checking first means at iteration i the seen-map only contains indices strictly less than i — no self-match is possible.

The approach

Walk once with a hash map of value→index. For each x, check whether the complement target−x was already seen before inserting x. Check-before-insert avoids matching an element with itself.

AspectValue
PatternHash map
Recognise it byFind a pair summing to a target; unsorted input.
Time complexityO(n)
Space complexityO(n)
DifficultyEasy

Who asks it

Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.