We are given an array asteroids of integers representing asteroids in a row.
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.
?
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
From: LeetCode
Link: 735. Asteroid Collision
To solve the “Asteroid Collision” problem in C, we need to implement the asteroidCollision function. This function takes an array of integers representing the asteroids, along with their size, and returns the state of the asteroids after all collisions have been resolved.
The key idea here is to use a stack to keep track of the asteroids. We iterate through the given array of asteroids and for each asteroid, we check for possible collisions. If an asteroid is moving to the right (positive integer), we push it onto the stack. If it’s moving to the left (negative integer), we check for collisions with the asteroids currently on the stack (which are moving to the right). We pop asteroids from the stack if they are smaller than the current left-moving asteroid. If we encounter an asteroid of the same size but in the opposite direction, both asteroids explode and we don’t add the current asteroid to the stack.
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* asteroidCollision(int* asteroids, int asteroidsSize, int* returnSize) {
int* stack = (int*)malloc(asteroidsSize * sizeof(int));
int top = -1;
for (int i = 0; i < asteroidsSize; i++) {
// If asteroid is moving right or stack is empty, push to stack
if (asteroids[i] > 0 || top == -1) {
stack[++top] = asteroids[i];
} else {
while (top != -1 && stack[top] > 0 && stack[top] < -asteroids[i]) {
top--; // Pop smaller right-moving asteroids
}
if (top != -1 && stack[top] == -asteroids[i]) {
top--; // Both asteroids explode
} else if (top == -1 || stack[top] < 0) {
stack[++top] = asteroids[i]; // Add left-moving asteroid
}
// If stack[top] > -asteroids[i], do nothing (right-moving asteroid survives)
}
}
*returnSize = top + 1;
return stack;
}