Loading…
Two Sum is a easy coding interview question covering hash maps, arrays — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given an array of integers `nums` and an integer `target`, return the indices of the two numbers that add up to `target`.
You may assume exactly one solution exists, and you may not use the same element twice.
Example: nums = [2,7,11,15], target = 9 → [0,1]
Try it yourself first
In an interview you'd get about 15 minutes for a easy question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Array [2, 7, 11, 15] target = 9
Hashmap seen = {}
Variables
| 1 | def two_sum(nums, target): |
| ▶ | seen = {} |
| 3 | for i, num in enumerate(nums): |
| 4 | complement = target - num |
| 5 | if complement in seen: |
| 6 | return [seen[complement], i] |
| 7 | seen[num] = i |
| 8 | return [] |
Initialize an empty hashmap `seen` to store each number and its index as we scan.
Time
O(n)
Space
O(n)
Brute force: check every pair
O(n^2) time, O(1) space
Correct, and worth saying out loud in an interview as your starting point - but only if you immediately follow it with the hash map. Left as the final answer it fails the question.
Sort the array, then walk it with two pointers
O(n log n) time, O(n) space
This is the usual 'you can do it without a hash map' suggestion, and on THIS problem it loses twice. It is slower than O(n), and because the answer must be the original INDICES you have to carry each value's position through the sort, so it does not save space either. It becomes the right answer when the input is already sorted - that is Two Sum II, where two pointers run in O(1) extra space and beat the hash map.
Use a hash map to store each number's index as you iterate. For each number, check if (target - number) is already in the map. O(n) time, O(n) space.
A full interview loop is more than one round. These are the others, each with what is on the site for it.