Two Pointers in Python
Chapter 36: Two Pointers
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Two pointers from both ends
Keep two positions, L** at the start and **R at the end, look at the two items, and use what you see to move one (or both) inward, until they meet.
Why two pointers never miss: each move rules out a row of pairs
At every step, the pair being checked is the best hope for one of its two numbers, so if it fails, that number can be crossed off with all of its pairs.
Pointers moving the same way: read and write
A read pointer R visits every item once, and a write pointer W marks where the next item worth keeping goes; everything left of W is the finished answer.
The most water, and three-sum
Start with the widest pair, and always move the shorter wall inward, because keeping it can never do better.
Trapping rain water
The water above a bar is min(tallest wall to its left, tallest wall to its right) - its height, and two pointers moving in from the ends can settle a bar on the side whose tallest wall so far is lower, because that lower wall is the one that decides.