Two-sum with a hash map
Given a list of numbers and a target, find the two whose values add up to that
target. The obvious approach checks every pair - but that is slow, and there is
a much better way that only walks the list once.
The trick is to trade a little memory for speed. As you move through the list,
keep a dict of every value you have already seen and where it was. For each new
number, the partner it needs is target - number. If that partner is already
in your dict, you are done - you have both indices. If not, record the current
number and move on. Each value gets looked up in constant time, so the whole
search is a single pass.
Your task: write two_sum(nums, target) that returns the two indices
whose values add up to target (in any order), or None if no such pair
exists. Assume at most one valid pair.
You'll practice:
- Using a dict as a lookup table you build as you go
- Turning a slow all-pairs check into a single-pass scan