Asteroid Collision
Simulate asteroid collisions where absolute value is size and sign is direction (+ right, - left).
- 2 <= asteroids.length <= 10⁴
- -1000 <= asteroids[i] <= 1000
- asteroids[i] != 0
asteroids = [5,10,-5][5,10]asteroids = [10,2,-5][10]asteroids = [8,-8][]Asteroid collisions only happen when two asteroids move toward each other. In this universe, that only happens when a Right-moving (+) asteroid is to the left of a Left-moving (-) one.
Think of it as a line of Defenders (Right-moving) waiting for an incoming Attacker (Left-moving). When an Attacker arrives, it must pass through a Gauntlet of every Defender it encounters.
We use a Stack to track our current line of survivors.
1. Moving Right: These asteroids are "Defenders." They never collide with each other, so they just join the end of the line (Stack).
2. Moving Left: This asteroid is an "Attacker." It looks at the very last Defender in the line (the Stack Top):
- If the Attacker is bigger: It smashes the Defender (Pop) and moves on to the next one in line. It keeps going until it's destroyed or the line is empty.
- If they are equal: Both are annihilated. The Defender leaves the line, and the Attacker disappears.
- If the Defender is bigger: The Attacker is immediately destroyed. The line remains unchanged.
3. Breakthrough: If an Attacker smashes through the entire line and finds the universe empty (or only finds other Left-moving survivors), it becomes a permanent survivor and joins the Stack itself.
stack = []
FOR asteroid in asteroids:
IF asteroid > 0:
stack.PUSH(asteroid)
ELSE:
// Attacker arrives! Resolve collisions
WHILE stack is NOT empty AND stack.PEEK() > 0 AND stack.PEEK() < ABS(asteroid):
stack.POP() // Defender destroyed
IF stack is NOT empty AND stack.PEEK() == ABS(asteroid):
stack.POP() // Both destroyed
ELSE IF stack is empty OR stack.PEEK() < 0:
stack.PUSH(asteroid) // Attacker survives
// ELSE: stack.PEEK() > ABS(asteroid), Attacker is destroyed (do nothing)
RETURN stackStack-based multi-collision chain reaction
Mental Model
- Stack as History: The stack tracks asteroids currently flying Right (+). They are the potential targets for incoming Left (-) asteroids.
- Cascading Collisions: A single incoming (-) asteroid can trigger a chain reaction, destroying multiple (+) asteroids in the stack until it meets its match or survives.
- Momentum: (-, +) never collide because they are already moving away from each other. (+, -) is the only collision case.
Interaction Physics
1. Positive (+) flies Right. 2. Negative (-) flies Left. 3. Larger Mass survives. 4. If Equal Mass, both are destroyed. 5. Only Right-Left pairs collide.