⚡Flashcard Drill➔
NeetCode #354LC-735MediumStackNC 250
← Back to All Problems

#354 · #735 · Asteroid Collision(小行星碰撞)

📌 Problem Statement & Constraints

We are given an array asteroids of integers representing asteroids in a row. The absolute value is the size and the sign is the direction (positive = right, negative = left). When two asteroids collide, the smaller explodes; equal sizes both explode. Asteroids moving in the same direction never collide. Return the state after all collisions. Constraints: 2 <= asteroids.length <= 10^4, -1000 <= asteroids[i] <= 1000, no zero values.

💡 Core Algorithmic Approaches

  1. A stack holds the surviving asteroids. A collision can only happen between a right-moving asteroid on the stack and a left-moving asteroid arriving.
  2. So the loop condition is a < 0 and stack and stack[-1] > 0.
  3. Resolve each collision: pop if the stack top is smaller, break if it is larger, and pop both if equal.
  4. Use an alive flag so the incoming asteroid is only pushed if it survives every collision.

💻 Benchmark Python3 Implementation

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        st = []
        for a in asteroids:
            alive = True
            # only a left-mover can collide with a right-mover on the stack
            while alive and a < 0 and st and st[-1] > 0:
                if st[-1] < -a:            # stack top explodes
                    st.pop()
                elif st[-1] == -a:         # both explode
                    st.pop()
                    alive = False
                else:                      # incoming explodes
                    alive = False
            if alive:
                st.append(a)
        return st

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each asteroid is pushed once and popped at most once.
💾 Space Complexity
O(n) for the stack.

⚠️ Interview Pitfalls & Follow-ups

  • Comparing st[-1] with a directly: a is negative, so the magnitudes must be compared via -a.
  • Allowing collisions between same-direction asteroids: the a < 0 and st[-1] > 0 guard is what restricts collisions to opposing pairs.
  • Forgetting the alive flag: an asteroid that explodes must not be pushed.
  • Popping both on an unequal collision: only the smaller one explodes.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

小行星碰撞

给定一个整数数组 asteroids,表示在同一行的小行星。对于数组中的每一个元素,其绝对值表示小行星的大小,正负表示小行星的移动方向(正表示向右移动,负表示向左移动)。每一颗小行星以相同的速度移动。找出碰撞后剩下的所有小行星。碰撞规则:两个小行星相互碰撞,较小的小行星会爆炸。如果两颗小行星大小相同,则两颗小行星都会爆炸。两颗移动方向相同的小行星,永远不会发生碰撞。约束:2 ≤ asteroids.length ≤ 10^4;-1000 ≤ asteroids[i] ≤ 1000;asteroids[i] != 0。

核心要点

  • 栈模拟碰撞(标准解) :遍历小行星,用一个栈保存「已确定存活」的小行星。
  • 何时可能碰撞 :只有「栈顶向右(正)且当前向左(负)」时才会碰撞。其他组合(同向、栈顶向左、当前向右)都不会碰撞。
  • 碰撞循环 :反复比较栈顶与当前小行星——栈顶更小则弹出继续比较;相等则两者都消失;栈顶更大则当前小行星爆炸。
  • 用一个标志表示当前小行星是否存活 ,只有存活才入栈。

常见陷阱

  • 不判断碰撞条件就盲目比较 :只有「栈顶正、当前负」才碰撞。漏掉判断会让同向小行星错误地互相抵消。
  • 相等时只弹出一个 :大小相同时两者都爆炸,必须 alive = False 且弹出栈顶。
  • 用 while 但忘记 alive 条件 :当前小行星已爆炸却继续比较,会产生错误结果。
  • 碰撞后忘记继续比较 :一个向左的大行星可能连续撞碎多个向右的小行星,必须用 while 循环。

参考实现

class Solution:
    def asteroidCollision(self, asteroids: list[int]) -> list[int]:
        stack = []
        for a in asteroids:
            alive = True
            # 只有「栈顶向右、当前向左」才碰撞
            while alive and a < 0 and stack and stack[-1] > 0:
                if stack[-1] < -a:
                    stack.pop()             # 栈顶更小,爆炸,继续比较
                elif stack[-1] == -a:
                    stack.pop()             # 大小相同,两者都爆炸
                    alive = False
                else:
                    alive = False           # 当前更小,爆炸
            if alive:
                stack.append(a)
        return stack