26/36
Part 7 of 8 · The worked exampleLearn and do

Simulating one collision per scan is O(n²)

The obvious answer: find the first right-mover directly followed by a left-mover, settle that collision, and start the scan over:

def collide_rounds(rocks):
    rocks = list(rocks)
    while True:
        for i in range(len(rocks) - 1):
            if rocks[i] > 0 and rocks[i + 1] < 0:
                a, b = rocks[i], -rocks[i + 1]
                if a > b:
                    del rocks[i + 1]
                elif a < b:
                    del rocks[i]
                else:
                    del rocks[i:i + 2]
                break
        else:
            return rocks


rocks = [4, 7, -3, 2, -9, 6, -6, -1, 5]
print(collide_rounds(rocks))
[-9, -1, 5]

Each round scans up to n rocks and removes one or two, so it's O(n²). Say that, and move on.

Keep the survivors on a stack, and let each left-mover fight the top

Read the rocks left to right, and keep the survivors so far on a stack. The survivors never threaten each other, so the stack is settled.

  • A right-mover goes on top. Nothing to its left can reach it, and whatever might hit it hasn't arrived yet.
  • A left-mover meets the right-movers on the stack nearest first, which is the top. It breaks every smaller one it reaches, stops at a bigger one, and breaks up along with an equal one. If it gets past every right-mover, it joins the stack for good.

Trace it the way you'd narrate it at the whiteboard:

RockWhat happensSurvivors, top on the right
4push4
7push4, 7
-3breaks on 74, 7
2push4, 7, 2
-92, then 7, then 4 break-9
6push-9, 6
-66 and -6 both break-9
-1nothing moving right to hit-9, -1
5push-9, -1, 5

The -9 shows the stack at work. It pops the 2, the 7 and the 4, nearest first, and then it's the bottom of the stack. The survivors, [-9, -1, 5], are the same as collide_rounds gives.

In the editor is collide, the stack version, with one change to its while condition. It gives the wrong survivors for the worked example's row. Use the trace table to find the bug, and fix it.