Two Pointers
20 / 170Two PointersLesson 5 of 6About 69 min
The unit's hardest idea: pointers that remember a running value, and a decision that depends on which side is settled.
So far the answer has been a single number found by comparing two ends. Now consider problems where every position contributes something, and its contribution depends on what lies on both sides of it.
The concrete version: given a row of column heights, how much water sits on top of the row after rain? The total is a sum over columns, and no column can be worked out by looking at itself.
The array version and the pointer version are both O(n) time. One is O(n) space and easy to justify; the other is O(1) space and needs the settled-side argument. Knowing both, and being able to say why the second one is correct, is a stronger position than only knowing the second.
Write the array version first, get it passing, then collapse it. Attempting the pointer version cold is how people end up with a loop that is nearly right and no way to tell which half is wrong.
tallest_to_left returns a list where position i holds the tallest value strictly to the left of i, or 0 if there is nothing there. tallest_to_right does the mirror. visible_from_either_end uses both: a post is visible if it is taller than everything on at least one of its two sides.
Tests
print(tallest_to_left([3, 1, 4, 2]))print(tallest_to_right([3, 1, 4, 2]))print(visible_from_either_end([3, 1, 4, 2]))print(visible_from_either_end([1, 2, 3]), visible_from_either_end([]), visible_from_either_end([5]))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.