735. Asteroid Collision
Asked at 35Amazon61Meta43Microsoft43Bloomberg39Google37Nutanix60DE Shaw58Salesforce55Infosys45Visa39Qualtrics100Dream1189Roku87Sprinklr72SoFi69PhonePe64Accolite64Oracle64PayPal63Nuro60Meesho57ServiceNow55Nvidia55Uber55Zoho52Flipkart52Deloitte50OpenAI49Juspay47DoorDash45IBM44Walmart Labs43TikTok41tcs36Goldman Sachs33
Problem
Asteroids move along a line: |value| is the size, the sign is the direction (positive right, negative left), all at the same speed. When two collide the smaller one explodes; equal sizes both explode. Asteroids moving the same way never meet. Return the state after all collisions.
Example: [5,10,-5] → [5,10]; [8,-8] → []; [10,2,-5] → [10]
Only a right-mover (stack top > 0) followed by a left-mover (x < 0) collide. While that happens, the smaller explodes; equal sizes both explode.
Complexity: O(n).
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
st = []
for x in asteroids:
alive = True
while alive and x < 0 and st and st[-1] > 0:
if st[-1] < -x:
st.pop()
continue
if st[-1] == -x:
st.pop()
alive = False
if alive:
st.append(x)
return st
assert Solution().asteroidCollision([5, 10, -5]) == [5, 10]
assert Solution().asteroidCollision([8, -8]) == []
assert Solution().asteroidCollision([10, 2, -5]) == [10]
assert Solution().asteroidCollision([-2, -1, 1, 2]) == [-2, -1, 1, 2]
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> st = new ArrayDeque<>();
for (int x : asteroids) {
boolean alive = true;
while (alive && x < 0 && !st.isEmpty() && st.peekLast() > 0) {
int top = st.peekLast();
if (top < -x) { st.pollLast(); continue; }
if (top == -x) st.pollLast();
alive = false;
}
if (alive) st.addLast(x);
}
return st.stream().mapToInt(Integer::intValue).toArray();
}
}
func asteroidCollision(asteroids []int) []int {
st := []int{}
for _, x := range asteroids {
alive := true
for alive && x < 0 && len(st) > 0 && st[len(st)-1] > 0 {
top := st[len(st)-1]
if top < -x { // the stack top explodes, keep going
st = st[:len(st)-1]
continue
}
if top == -x {
st = st[:len(st)-1]
}
alive = false
}
if alive {
st = append(st, x)
}
}
return st
}