Hashing for lookups: Two Sum

When you catch yourself asking "have I seen the value that completes this one?", use a dict. A dict lookup is O(1) on average, so one pass replaces a loop inside a loop.

Two Sum is the classic. For each number x, the partner you need is target - x. Keep a dict from value to index of everything seen so far. If the partner is already in it, you are done. Otherwise store x.

The brute force checks every pair: O(n²). The dict version is O(n) time and O(n) extra space.

A common mistake: storing x before checking for its partner. Then [3, 4] with target 6 pairs 3 with itself.

Exercise: finish two_sum so it returns the indices (i, j) with i < j of the two numbers that add up to target, or None if no pair does. Assume at most one answer. It must be O(n): the speed test uses a list where the pair is at the very end. Press Check to run the tests.