Find two numbers that add up to the target in one pass, by remembering what you have seen in a dictionary.
Python · intermediate · 6 min · 20 steps · free
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
need = target - n
if need in seen:
return [seen[need], i]
seen[n] = i
return None
print(two_sum([3, 8, 5, 2], 7))two_sum(). Its body does not run yet: it runs each time the function is called.two_sum(), with nums = [3, 8, 5, 2] and target = 7. It gets its own names.seen is created and points to a new dict: {}.i is created with the value 0. n is created with the value 3.need in seen is false, so the block under it is skipped.i changes from 0 to 1. n changes from 3 to 8.need changes from 4 to -1.need in seen is false, so the block under it is skipped.8 with the value 1 is added to the dict that seen points to.i changes from 1 to 2. n changes from 8 to 5.need changes from -1 to 2.need in seen is false, so the block under it is skipped.5 with the value 2 is added to the dict that seen points to.i changes from 2 to 3. n changes from 5 to 2.need changes from 2 to 5.seen has it, at index 2.[seen[need], i].two_sum() has finished, so its names are gone. It prints [2, 3].seen before checking, which can pair a number with itselfAnswer: O(n²)
Answer: O(n)
← How a Hash Table Works · Tree Traversal →