Warm-up tutorial

Big O and hash mapsWorld 1 tutorial
0:00 / 0:00

Before the first stage: how the work grows as the input grows, and the hash map, which answers "have I seen this?" in one hop.

▼

Transcript

Warm-up. Before the first stage, one idea you'll use everywhere: Big O. It doesn't count seconds. It describes how the work grows as the input grows.

The slow way is to compare every pair. Ten items make forty-five pairs. Double the items, and the pairs roughly quadruple: that's O of n squared. At a hundred thousand items, one pass is a hundred thousand steps, but every pair is about five billion. One takes a blink; the other, minutes.

So open the toolbox. The first tool is a hash map, a wall of lockers. Each value's locker is worked out from the value itself, so asking if eleven is inside takes one hop. That's O of one, on average.

Here's the clue to watch for. If you're comparing every pair, ask what you could remember instead.

Does a list have a repeat? Walk it once. At each item, check its locker, then store it. When seven comes back, its locker already holds a seven. One pass that remembers turns O of n squared into O of n.

Now let's put it to work on Two Sum.