↓Skip to main content
  1. LeetCode/

LeetCode 735: Asteroid Collision

·2 mins· ·
LeetCode Medium Array Stack Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-04-18

  • Submissions: Wrong Answer → Runtime Error → Wrong Answer → Output Limit Exceeded → Accepted

Approach
#

Scanning left to right (Stack Template 2), a collision happens only when the stack top moves right (> 0) and the current asteroid moves left (< 0):

  • A smaller top explodes, and the comparison continues with the new top.
  • Equal sizes both explode.
  • A larger top destroys the current one.

A surviving asteroid is pushed. A left-mover meeting an empty stack or a left-moving top never collides.

My Attempts
#

In 2024 I scanned right to left with a second stack for left-movers:

  • Attempt 1 never added the remaining left-movers back to the answer: [-4, 2] returned [2].
  • After that, it compared against rev_stack[0], the farthest one, instead of the nearest rev_stack[-1]: [2, -4, -1] returned [-4] instead of [-4, -1]. Using [-1] passed, after one Output Limit Exceeded from a print.

Solution
#

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        st = []
        for a in asteroids:
            alive = True
            while alive and a < 0 and st and st[-1] > 0:
                if st[-1] < -a:
                    st.pop()
                elif st[-1] == -a:
                    st.pop()
                    alive = False
                else:
                    alive = False
            if alive:
                st.append(a)
        return st

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Only a right-mover on the left meeting a left-mover on the right collides; [-4, 2] does not.
  • Compare with the nearest asteroid, the top st[-1], not st[0].

Interview Explanation
#

Scanning left to right with a stack, only a right-moving top and a left-moving current asteroid collide: a smaller top explodes and the check continues, equal sizes both vanish, and a larger top stops the current one; survivors are pushed. Each asteroid enters and leaves once, so time is O(n).

Related

LeetCode 54: Spiral Matrix
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 54 note: keep four boundaries and walk right, down, left and up, shrinking a boundary after each side
LeetCode 59: Spiral Matrix II
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 59 note: keep four boundaries as in LC 54, but fill in 1 to n² instead of reading
LeetCode 682: Baseball Game
·1 min
LeetCode Easy Array Stack Simulation
LeetCode 682 note: keep valid scores on a stack; C removes the last, D adds its double, and + adds the sum of the last two
LeetCode 1814: Count Nice Pairs in an Array
·1 min
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 note: rearrange the condition into nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]), count pairs per value, and remember the modulus
LeetCode 3075: Maximize Happiness of Selected Children
·1 min
LeetCode Medium Array Greedy Sorting
LeetCode 3075 note: choose k children from the happiest, where the i-th choice loses i, floored at 0
LeetCode 3070: Count Submatrices with Top-Left Element and Sum Less Than k
·2 mins
LeetCode Medium Array Matrix Prefix-Sum
LeetCode 3070 note: submatrices containing the top-left corner are exactly the 2D prefix sums P[i][j]; count those <= k