This is THE most famous coding interview question — LeetCode #1: Two Sum. If you're going to master one problem, make it this one.
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target.
Example:nums = [2, 7, 11, 15], target = 9
→ [0, 1] because nums[0] + nums[1] = 2 + 7 = 9
Brute Force — O(n²): Try every pair.
Optimal — O(n) using HashMap:
The key insight: if we need a + b = target, then b = target - a. We can look up b in a hash map in O(1)!
💭 Challenge time! Now implement this yourself using the strategy above. The best way to learn is by doing! ⭐
How it works step by step:
Complexity: Time O(n), Space O(n)
def twoSum(nums, target):
hashmap = {} # value → index
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
twoSum([2, 7, 11, 15], 9)
[0, 1]
twoSum([3, 2, 4], 6)
[1, 2]
twoSum([3, 3], 6)
[0, 1]