Skip to content
BytePatterns

Colliding Rocks in a Row

MediumStacks & Queues#stack#pop-while-weaker~25m

Problem

Rocks move along a line at the same speed. Each is given as a nonzero integer: the absolute value is its size, and the sign is its direction, positive for right and negative for left. When two rocks meet, the smaller one breaks; if they are the same size, both break. Rocks moving in the same direction never meet. Return the rocks that remain after every collision, in their original order. There are between 2 and 10,000 rocks, and each size is at most 1,000.

Examples

Input:  rocks = [5, 10, -5]
Output: [5, 10]
Why:    -5 meets 10 and breaks; 5 and 10 move the same way and never meet
Input:  rocks = [10, 2, -5]
Output: [10]
Why:    -5 breaks 2, then meets 10 and breaks itself
Input:  rocks = [8, -8]
Output: []
Why:    edge case, equal sizes break each other

Hints

0 / 3

Stuck on the idea rather than the code? Monotonic Stack covers it.