Test the edges you named, then give the cost
Here's the fixed collide. The while runs only while the new rock moves left and the top of the stack moves right:
def collide(rocks):
survivors = []
for rock in rocks:
alive = True
while alive and rock < 0 and survivors and survivors[-1] > 0:
top = survivors[-1]
if top <= -rock:
# the rock on the stack breaks
survivors.pop()
if top >= -rock:
# the new rock breaks
alive = False
if alive:
survivors.append(rock)
return survivors
print(collide(rocks))
[-9, -1, 5]
Before you say you're done, run collide on the edge cases you named at the start.
for row in [[], [3, -3], [-2, -1, 1, 2], [1, -2, 3], [5, 5, -5]]:
print(f"{str(row):16} {collide(row)}")
[] []
[3, -3] []
[-2, -1, 1, 2] [-2, -1, 1, 2]
[1, -2, 3] [-2, 3]
[5, 5, -5] [5]
[3, -3] breaks both. [-2, -1, 1, 2] comes back unchanged, since nothing meets. In [5, 5, -5], the -5 breaks along with the nearer 5 and never reaches the other one. The two versions also agreed on 2,000 random rows of up to 12 rocks.
Each rock is pushed at most once and popped at most once, the same argument as the monotonic stack: O(n) time and O(n) memory. Measured on n - 1 rocks of size 1 moving right, then one of size n moving left, where the simulation finds one collision per scan, best of 3 runs or more:
| n | collide_rounds | collide |
|---|---|---|
| 1,000 | 15.1 ms | 0.103 ms |
| 2,000 | 67.6 ms | 0.208 ms |
| 4,000 | 274.4 ms | 0.410 ms |
| 8,000 | 1,136.5 ms | 0.837 ms |
The two versions were checked with a random test. In the editor, write first_disagreement(fast, slow, seed): it gets two functions, tries 2,000 random rows, and returns the first row where they differ. The demo line passes sorted and list, which disagree on most rows, so you see a failure come back.