Asteroid Collision

Monotonic Stack & Queue Problems DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Asteroid Collision problem in data structures and algorithms, Stack, Arrays, Time Complexity, Space Complexity, Algorithm, Conditional Statements, Loops, stack, simulation, array traversal, collision handling, time complexity analysis, Data Structure Operations.

Asteroid Collision We are given an array asteroids of integers representing the sizes of asteroids. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive means moving right, negative means moving left). All asteroids move at the same speed. When two asteroids meet, the smaller one explodes. If both are the same size, both explode. Two asteroids moving in the same direction will never meet. Find the state of all asteroids after all collisions. Input Specification: The input consists of a single line containing space separated integers representing the sizes and directions of the asteroids. Each integer asteroids[i] will be between 1000 and 1000, non zero. Output Specification: Output a single line containing space separated integers representing the sizes and directions of the remaining asteroids, in their original relative order. Constraints: 1 <= asteroids.length <= 10^4 1000 <= asteroids[i] <= 1000 asteroids[i] != 0 Sample Test Cases: Sample Input 1: 5 10 5 Sample Output 1: 5 10 Explanation: 10 and 5 collide. 10 is larger, so 5 explodes. The remaining asteroids are [5, 10]. Sample Input 2: 8 8 Sample Output 2: ` Explanation: 8 and 8 collide. They are the same size, so both explode. No asteroids remain. Sample Input 3: 10 2 5 Sample Output 3: 10 Explanation: 10 and 2 collide. 10 is larger, so 2 explodes. The remaining asteroids are [10]. Then 10 and 5 collide. 10 is larger, so 5 explodes. The remaining asteroid is [10]. Sample Input 4: 2 1 1 2 Sample Output 4: 2 1 1 2` Explanation: No collisions occur because all asteroids are moving in the same direction or away from each other.