Asteroid Collision

Stack / Queues Monotonic Stack Medium

Given an array of integers asteroids, where each integer represents an asteroid in a row, determine the state of the asteroids after all collisions. In this array, the absolute value represents the size of the asteroid, and the sign represents its direction (positive meaning right and negative meaning left). All asteroids move at the same speed.


When two asteroids meet, the smaller one will explode. If they are the same size, both will explode. Asteroids moving in the same direction will never meet.

Examples:

Input: asteroids = [2, -2]

Output: []

Explanation: The asteroid with size 2 and the one with size -2 collide, exploding each other.

Input: asteroids = [10, 20, -10]

Output: [10, 20]

Explanation: The asteroid with size 20 and the one with size -10 collide, resulting in the remaining asteroid with size 20. The asteroids with sizes 10 and 20 never collide.

Input: asteroids = [10, 2, -5]

Constraints

·  2 <= asteroids.length <= 105

·  -106 <= asteroids[i] <= 106

·  asteroids[i] != 0

Hints

  • Iterate through the list, pushing positive asteroids onto a stack since they are moving right.
  • When encountering a negative asteroid, check against the stack. If the top of the stack is a positive asteroid, simulate a collision. If the negative asteroid survives, continue checking until it is either destroyed or pushed onto the stack. The stack maintains the final state of the surviving asteroids.

Company Tags

Dropbox Epic Systems Splunk IBM Reddit Visa Broadcom AMD Flipkart Pinterest ARM Zomato Zynga GE Healthcare Electronic Arts Robinhood Stripe Walmart Etsy Target Red Hat Intel Teladoc Health Johnson & Johnson Airbnb Google Microsoft Amazon Meta Apple Netflix Adobe