Skip to content

Hash maps and sets · routine

Two sum

Write two_sum(nums, target) returning [i, j] with i < j and nums[i] + nums[j] == target, choosing the smallest j that works. Return [] if there is no such pair.

For each number, the partner you need is target - number. A dictionary from value to index tells you in one step whether you have already passed it.

Run adds print(two_sum([2, 7, 11, 15], 9)) after your code, to try it.

Stuck on the idea rather than the code? The Hash maps and sets lesson walks through it.