Asteroid Collision — LeetCode 735 Python Solution

MediumStackArraySimulation
Problem
#735
Pattern
Stack
Reading time
3 min

The problem

We are given an array asteroids of integers representing asteroids in a row. The indices of the asteroid in the array represent their relative position in space.

Example

Input
asteroids = [5,10,-5]
Output
[5,10]
Explanation
The 10 and -5 collide resulting in 10. The 5 and 10 never collide.

Python solution

Python
class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        stk = []
        for x in asteroids:
            if x > 0:
                stk.append(x)
            else:
                while stk and stk[-1] > 0 and stk[-1] < -x:
                    stk.pop()
                if stk and stk[-1] == -x:
                    stk.pop()
                elif not stk or stk[-1] < 0:
                    stk.append(x)
        return stk

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 735. Asteroid Collision is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 735. Asteroid Collision?
LeetCode 735. Asteroid Collision is rated Medium on LeetCode.
What is the time complexity of LeetCode 735. Asteroid Collision?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 735. Asteroid Collision?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 735. Asteroid Collision cover?
LeetCode 735. Asteroid Collision is tagged Stack, Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview