Remember the Two Sum problem from the Arrays chapter? We solved it with nested loops in O(n²). Now let's crush it in O(n) using a hash map!
The insight: for each number, calculate its complement (target - num). If the complement is already in our hash map, we found our pair!
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
This is the classic example of trading space for time — we use O(n) extra space to get O(n) time instead of O(n²).
def two_sum(nums, target):
seen = {} # value → index
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
two_sum([2, 7, 11, 15], 9)
[0, 1]