Two Sum
Find the two positions whose values add up to a target. A one-pass hash map answers it in O(n) time.
Walk the array once. For each number x, ask: have I already seen target − x? A hash map stores every number you have passed, so its partner is found in O(1) average time. That turns the O(n^2) pair scan into a single pass.
Builds on
- Hash map lookup — The one-pass solution is that pattern applied to complements, so the query-then-insert order must be second nature.
- Two pointers — The sorted alternative in this lesson is the converging sweep from that pattern.
What Two Sum asks
Given an array nums of integers and a number target, return the indices of two different positions whose values add up to target. The problem promises exactly one solution, so you never choose between answers. The output is a pair of indices, not a pair of values, and the two indices must differ.
| nums | target | Answer | Why |
|---|---|---|---|
| [2, 7, 11, 15] | 9 | [0, 1] | 2 + 7 = 9 |
| [3, 2, 4] | 6 | [1, 2] | 2 + 4 = 6; the 3 cannot pair with itself |
| [3, 3] | 6 | [0, 1] | two different positions hold the same value |
| [-1, -2, -3, -4, -5] | -8 | [2, 4] | -3 + -5 = -8 |
Read the spec aloud before coding and confirm three things: the answer is indices, the two positions must differ, and the input is not sorted. The third fact matters most. Sorting would move the values away from their original positions, and the answer must report those positions.
Check yourself
What does twoSum([3, 2, 4], 6) return?
Brute force: check every pair
The direct approach tries every pair of different positions. The outer loop fixes i, and the inner loop tries every j after it. Each unordered pair is checked exactly once.
function bruteForce(nums, target) { let checks = 0; for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { checks++; if (nums[i] + nums[j] === target) return { pair: [i, j], checks }; } } return { pair: null, checks };}On [2, 7, 11, 15] with target 9, the first pair (0, 1) already matches, so brute force makes 1 check. The worst case is a target with no match. Then all C(4,2) = 4 x 3 / 2 = 6 pairs run. On [11, 2, 15, 7] with target 9, the answer is at (1, 3). The checks run in order (0,1), (0,2), (0,3), (1,2), (1,3), so brute force makes 5 checks.
| n | Brute force C(n,2) | Map version: n lookups | Ratio |
|---|---|---|---|
| 4 | 6 | 4 | 1.5x |
| 1,000 | 499,500 | 1,000 | 499.5x |
| 100,000 | 4,999,950,000 | 100,000 | 49,999.5x |
Brute force is O(n^2) time because the pair count grows with the square of n. It needs O(1) extra space, so it is a reasonable fallback only when n is tiny or memory is truly tight. At 10^9 simple operations per second, the 4,999,950,000 checks at n = 100,000 take about 5 seconds, which is far too slow for a typical time limit.
Check yourself
How many pairs does brute force check in the worst case for n = 4?
One pass with a hash map
Instead of searching the earlier numbers for a partner each time, store them in a hash map keyed by value, with the index as the stored value. For a number x at index i, the partner must be target − x. One average O(1) lookup tells you whether that partner is already in the map.
Query first
look up target − nums[i] in the map. At this point the map holds only indices 0 to i − 1.
Hit
if the partner is there, return [map.get(need), i]. The partner's index is smaller, so the pair comes out in order.
Miss
store nums[i] → i and move on. The number now waits as a partner for later positions.
Count the work on [2, 7, 11, 15] with target 9. At i = 0, the lookup for 7 misses and 2 → 0 is stored. At i = 1, the lookup for 2 hits at index 0 and the function returns [0, 1]. That is 2 iterations, 2 lookups and 1 insert. The values 11 and 15 are never read. On [11, 2, 15, 7] the same code takes 4 iterations, 4 lookups and 3 inserts before the hit at i = 3. The work grows with n, not with n squared. The complete function is the lesson code.
Check yourself
In [3, 3] with target 6, what does a version that inserts before querying return?
The alternative: sort and use two pointers
Sorting enables the two-pointer method. Put one pointer at each end. When the sum is too small, move the left pointer right. When it is too big, move the right pointer left. Sorted order makes each move safe, because the pointer skips only positions that cannot pair with the current value.
The catch is the indices. Sorting moves values, so each value must carry its original index. The code below sorts (value, index) pairs.
function twoSumSorted(nums, target) { const pairs = nums.map((value, index) => ({ value, index })); pairs.sort((a, b) => a.value - b.value); let l = 0, r = pairs.length - 1; while (l < r) { const sum = pairs[l].value + pairs[r].value; if (sum === target) return [pairs[l].index, pairs[r].index].sort((a, b) => a - b); if (sum < target) l++; else r--; } return null;}Trace [11, 2, 15, 7] with target 9. The sorted pairs are 2 (index 1), 7 (index 3), 11 (index 0) and 15 (index 2). The pointers start at 2 and 15: the sum 17 is too big, so r moves to 11. The sum 13 is too big, so r moves to 7. Then 2 + 7 = 9 is a hit. That is 3 sum checks, and the returned indices are 1 and 3.
| Method | Main work | Count | Extra space |
|---|---|---|---|
| brute force | pair checks | 5 checks | O(1) |
| hash map, one pass | iterations with a lookup and an insert | 4 iterations, 4 lookups, 3 inserts | O(n) |
| sort pairs, then two pointers | sum checks after the sort | 3 sum checks, plus the sort | O(n) for the pairs |
Sorted input is the exception. If the array is already sorted and the indices refer to that array, no sort or copy is needed. The sweep then costs O(n) time and O(1) extra space, which is the answer to the follow-up question in the interview section.
Check yourself
Why does the sorted version need an index field on each value?
Edge cases and what breaks them
| Input and target | Result | Which rule handles it |
|---|---|---|
| [3, 3], 6 | [0, 1] | the second 3 finds the first 3, which was stored earlier |
| [0, 4, 3, 0], 0 | [0, 3] | the second 0 finds the first 0; the 4 and the 3 pass without a match |
| [-1, -2, -3, -4, -5], -8 | [2, 4] | negatives need no special case, because -8 - (-3) = -5 is ordinary arithmetic |
| [1, 2, 4], 9 | null | the loop ends with no hit, so the function returns its no-answer value |
| [3], 6 | null | a single number has no partner; the map is empty when it is checked |
Duplicates are the subtle case. Equal values at different positions are valid pairs, so the map must be queried before the current value is inserted. If a value repeats without a match, the later index can overwrite the earlier one. Both copies are valid positions for that value, so the pair found later is still correct.
Return a value that callers can detect for no-answer inputs. This lesson's code returns null, and the codeReview rewrite below does the same. Silence is the bug to avoid: a function that falls off the end returns undefined, which looks like a result.
Check yourself
What does twoSum([0, 4, 3, 0], 0) return with the one-pass map?
Complexity and what interviewers listen for
The loop runs at most n times. Each iteration does one lookup and at most one insert, and each costs O(1) on average. So the time is n x O(1) = O(n). Before a hit, the map holds at most n − 1 entries, so the space is O(n). The best case is O(1): the first hit happens at i = 1, so the loop does almost no work.
O(1) is an average-case claim for hash tables. The worst case depends on the hash implementation, so say 'O(1) average' out loud.
01Restate (1 min)
Confirm the output is indices, there is one solution, and a position cannot be used twice.
02Brute force (2 min)
Describe the two loops and count them: C(n,2) pairs, which is 6 for n = 4.
03Insight (2 min)
Query the complement, then store the current number. Say why the order matters.
04Code (5 min)
Write the single loop with the query before the insert and a no-answer return.
05Dry run (2 min)
Trace [3, 3] with target 6 and point out where the query runs before the store.
06Cost (2 min)
State O(n) time and O(n) space, then name the sorted two-pointer trade-off and the sorted-input special case.
Recap
For each x, look up target − x among the numbers already stored.
Query the map before inserting the current number, so an element never pairs with itself.
Brute force checks up to C(n,2) = n(n − 1) / 2 pairs. The map version does one lookup per number.
Sorting enables two pointers, but returning original indices then needs (value, index) pairs: O(n log n) time and O(n) extra space.
Return a clear no-answer value such as null when no pair exists.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
two pointers
Moving two indices through an array to meet a condition in one pass instead of nested loops.
hash map
A key-value store with O(1) average lookup. Here the key is the number and the value is its index.
array
A contiguous block of memory holding items in order, readable by index in O(1).
RESTRepresentational State Transfer
An API style built on plain HTTP verbs (GET, POST, PUT, DELETE) where each URL names a resource.
complement
The partner value target − x that pairs with the current number x.
query before insert
Look up the complement first, then store the current number, so an element never pairs with itself.
C(n,2)
The number of unordered pairs of different positions among n values: n(n − 1) / 2.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixQuery before insert. With [3, 3] and target 6, store-first pairs the 3 at index 0 with itself and returns [0, 0] instead of [0, 1].
FixRe-read the spec. Classic Two Sum returns indices, and returning values fails any test that checks positions.
FixSorting moves positions. To use two pointers and still return original indices, sort (value, index) pairs, or use the map, which needs no sort.
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
A hash map stores each number's index as you walk the array, and for each number checks whether target minus the number was already seen. That is O(n) time and O(n) space. The brute force is O(n^2) time with O(1) extra space.
O(n) time · O(n) space
Real worldThis is a common warm-up question, and it tests whether you reach for a hash map by default.
DeeperMention both solutions and when each wins: the map when speed matters, brute force when memory is tight and n is small.