LeetCode 1 ·
Easy
Two Sum
Given an array and a target, return the indices of the two numbers that add up to the target.
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
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.
| Aspect | Value |
|---|---|
| Pattern | Hash map |
| Recognise it by | Find a pair summing to a target; unsorted input. |
| Time complexity | O(n) |
| Space complexity | O(n) |
| Difficulty | Easy |
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.