Arrays tutorial

Two pointers and sliding windowWorld 2 tutorial
0:00 / 0:00

Walk the array once with a little state instead of restarting everywhere: two pointers closing in from the ends, or a window that grows on the right and shrinks on the left.

▼

Transcript

Welcome to the Arrays world. The first move comes in two shapes: two pointers, and the sliding window.

The slow way starts over at every position: eight items take thirty-six steps, and that grows like n squared. Instead, walk the array once, carrying a little state, like the best so far.

Two pointers. On a sorted row, put one at each end, looking for a pair that adds to fourteen. One plus twelve is thirteen: too small, so the left one steps in. Three plus twelve is fifteen: too big, so the right one steps in. Three plus eleven: fourteen.

A sliding window keeps a running sum, at most eight. It adds on the right: three, one, two, four makes ten, too much. So it subtracts on the left: drop the three, and it's seven.

The clue: a contiguous subarray or substring, a pair in a sorted array, or the best so far.

Each pointer only moves one way: linear time, constant extra space.

Now let's use it on Best Time to Buy and Sell Stock.