Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input: asteroids = [3,5,-6,2,-1,4] Output: [-6,2,4] Explanation: The asteroid -6 makes the asteroid 3 and 5 explode, and then continues going left. On the other side, the asteroid 2 makes the asteroid -1 explode and then continues going right, without reaching asteroid 4.
Constraints:
2 <= asteroids.length <= 104-1000 <= asteroids[i] <= 1000asteroids[i] != 0Problem summary: 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. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack
[5,10,-5]
[8,-8]
[10,2,-5]
can-place-flowers)destroying-asteroids)count-collisions-on-a-road)robot-collisions)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #735: Asteroid Collision
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> stk = new ArrayDeque<>();
for (int x : asteroids) {
if (x > 0) {
stk.offerLast(x);
} else {
while (!stk.isEmpty() && stk.peekLast() > 0 && stk.peekLast() < -x) {
stk.pollLast();
}
if (!stk.isEmpty() && stk.peekLast() == -x) {
stk.pollLast();
} else if (stk.isEmpty() || stk.peekLast() < 0) {
stk.offerLast(x);
}
}
}
return stk.stream().mapToInt(Integer::valueOf).toArray();
}
}
// Accepted solution for LeetCode #735: Asteroid Collision
func asteroidCollision(asteroids []int) (stk []int) {
for _, x := range asteroids {
if x > 0 {
stk = append(stk, x)
} else {
for len(stk) > 0 && stk[len(stk)-1] > 0 && stk[len(stk)-1] < -x {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 && stk[len(stk)-1] == -x {
stk = stk[:len(stk)-1]
} else if len(stk) == 0 || stk[len(stk)-1] < 0 {
stk = append(stk, x)
}
}
}
return
}
# Accepted solution for LeetCode #735: Asteroid Collision
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
// Accepted solution for LeetCode #735: Asteroid Collision
impl Solution {
#[allow(dead_code)]
pub fn asteroid_collision(asteroids: Vec<i32>) -> Vec<i32> {
let mut stk = Vec::new();
for &x in &asteroids {
if x > 0 {
stk.push(x);
} else {
while !stk.is_empty() && *stk.last().unwrap() > 0 && *stk.last().unwrap() < -x {
stk.pop();
}
if !stk.is_empty() && *stk.last().unwrap() == -x {
stk.pop();
} else if stk.is_empty() || *stk.last().unwrap() < 0 {
stk.push(x);
}
}
}
stk
}
}
// Accepted solution for LeetCode #735: Asteroid Collision
function asteroidCollision(asteroids: number[]): number[] {
const stk: number[] = [];
for (const x of asteroids) {
if (x > 0) {
stk.push(x);
} else {
while (stk.length && stk.at(-1) > 0 && stk.at(-1) < -x) {
stk.pop();
}
if (stk.length && stk.at(-1) === -x) {
stk.pop();
} else if (!stk.length || stk.at(-1) < 0) {
stk.push(x);
}
}
}
return stk;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.