You get an array of numbers and a target. Exactly one pair of elements adds up to the target: return their indices. The same element can't be used twice.
Example: in [8, 3, 11, 6, 10, 4] with target 13, the answer is [1, 4], because 3 + 10 = 13 (indices count from 0).
Try it yourself first: LeetCode 1 ↗. Then step through the solution below.
Try every pair: add each element to every element after it and compare the sum with the target. Six elements make 15 pairs, and n elements make n(n − 1) / 2, so the time is O(n2). No extra memory is needed: O(1) space.
For each element x, its partner is not a mystery: it must be exactly target − x. So the question for every element is not "which element pairs with me?" but "have I already seen target − x?"
A hash map answers that in O(1) on average. Walk the array once: first look the partner up in the map, then add the current value with its index. When the second element of the pair arrives, its partner is already in the map.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
def two_sum(nums, target): seen = {} # value -> index for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return []
Now write it yourself on LeetCode 1 ↗, or go on: Valid Parentheses →
seen starts empty. It will hold each value already passed, with its index.x is 8, at index i = 0. Its partner need is 13 − 8 = 5, and seen has no 5.seen, with its index 0.seen yet: it comes later in the array.seen, with its index 1.seen has no 2.seen, with its index 2.seen has no 7.seen, with its index 3.seen, at index 1.seen each. That is O(n) time.| Approach | Time | Space |
|---|---|---|
| Brute force: try every pair | O(n2) | O(1) |
| Sort with the indices, then two indices from the ends | O(n log n) | O(n) |
| Hash map, one pass this page | O(n) | O(n) |
Note
O(1) is the hash map's average. When many keys collide, a lookup slows down: to O(n) in Python's dict and C++'s unordered_map. Java's HashMap turns a long chain of colliding keys into a balanced tree, which keeps its worst case near O(log n).
[5, 5] with target 10: the first 5 goes into the map at index 0, and the second finds it there: [0, 1]. The lookup comes before the insertion, so an element never pairs with itself.[5, 2, 8] with target 10: when 5 looks for 5, the map is still empty, so it is not paired with itself; 2 and 8 are: [1, 2].[-3, 4, 7] with target 4, 7 looks for 4 − 7 = −3 and finds it at index 0: [0, 2].The blocks below are steps of Two Sum in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example and on [5, 2, 8] with target 10, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 1 ↗, or go on: Valid Parentheses →
def two_sum(nums, target): seen = {} # value -> index for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return []What if the array is sorted? Then two indices, one at each end, are enough: if their sum is too small, move the left one right; if too large, move the right one left. That is O(n) time and O(1) space, with no map: Two Sum II (LeetCode 167). Sorting an unsorted array first costs O(n log n), and each value must carry its index through the sort, so the hash map stays the answer for the problem as asked.
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.