Given an array of integers and a target sum, find two numbers that add up to the target. Return their indices.
Two Sum is the quintessential coding interview warm-up. It tests your ability to optimize from brute force to an efficient solution, your knowledge of hash maps, and your skill at analyzing time-space tradeoffs.
Start with the brute-force O(n²) approach using nested loops to show you understand the problem.
Optimize to O(n) using a hash map: for each element, check if target minus the element exists in the map.
Walk through an example to validate your logic.
Discuss edge cases: duplicate values, no valid pair, negative numbers.
The brute-force approach checks every pair using two nested loops — O(n²) time, O(1) space. To optimize, I use a hash map. I iterate through the array once; for each number, I compute the complement (target minus current number) and check if it exists in the map. If yes, I return both indices. If not, I store the current number and its index in the map. This runs in O(n) time and O(n) space. For example, given [2, 7, 11, 15] with target 9: at index 0, complement is 7, not in map, store {2:0}. At index 1, complement is 2, found in map at index 0, so return [0, 1]. I always clarify with the interviewer whether the array is sorted (which allows a two-pointer O(1) space solution) and whether there can be multiple valid pairs.
Always start with brute force, then optimize — it shows structured thinking.
Ask if the array is sorted; if yes, a two-pointer approach uses O(1) space.
Clarify whether indices or values should be returned, and if the same element can be used twice.
Clarify with the interviewer. The classic problem asks for any one valid pair. If all pairs are needed, continue iterating after finding the first match.
Sorting takes O(n log n) and loses original indices. The hash map approach is better at O(n) while preserving indices.
Three Sum typically sorts the array and uses a two-pointer technique for each element, achieving O(n²) time.
HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.
Try HireMe AI Free