Difficulty: Easy | Asked at: Google, Amazon, Meta
Given an array of integers
nums and a target, return the indices of the two numbers that add up to target.python
nums = [2, 7, 11, 15]
target = 9
# Expected output: [0, 1]
You can't use the same element twice, and there's exactly one valid answer.
💡 Hint: Before you reach for a brute-force double loop, ask yourself - what if you could look up "have I seen the number I need?" in O(1)?
Try it yourself before scrolling for the solution 👇
Solution:
python
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Complexity: O(n) time, O(n) space - one pass, hash map lookup.
Common mistake: Candidates often solve this with nested loops (O(n²)) and stop there. If you already have the optimal solution, say it out loud early: "I can brute-force this in O(n²), but I think we can do better with a hash map." That sentence alone signals seniority.
What's the first approach that came to your mind? 🤔