Two Sum
How the interviewer asks it
“Given a list of integers and a target, return the indices of the two numbers that add up to the target. Exactly one pair exists, and you may not use the same element twice.”
4 9 2 7 11 15
0 1
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You state the brute force (check every pair, O(n²)) before optimising, so the interviewer sees you can reason from a baseline.
- You spot that the question is really "have I seen target minus this value before?", which a hash map answers in O(1).
- You handle duplicates such as [3, 3] with target 6 without matching an element with itself.
- You give time and space complexity without being asked.
How to structure your answer
- 01
Clarify
Ask whether there is always exactly one answer, whether values can be negative, and whether you return indices or values.
- 02
Brute force
Two nested loops over every pair. O(n²) time, O(1) space. Say it, do not code it.
- 03
One pass with a hash map
Walk the list once. For each value, look up target − value in a map from value to index. If it is there, return both indices; otherwise store the current value and index.
- 04
Test out loud
Run [2, 7, 11, 15] with target 9 and the duplicate case [3, 3] with target 6 through your code before saying you are done.
- 05
Complexity
O(n) time and O(n) space, trading memory for speed.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Inserting the value into the map before checking it, which pairs an element with itself.
- Sorting first to use two pointers and then returning indices from the sorted copy instead of the original positions.
- Jumping straight to code without saying the approach, so the interviewer cannot help when you get stuck.
- Not mentioning complexity until asked.
Follow-up questions to expect
- The list is now sorted and you may not use extra memory. (Two pointers from both ends: O(n) time, O(1) space.)
- Return every pair that adds up to the target, without duplicates.
- Extend it to three numbers that sum to zero.
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.