735. Asteroid Collision

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.
 

Example 1:
Example 2:
Example 3:
Constraints:
  • 2 < = a s t e r o i d s . l e n g t h < = 1 0 4 2 <= asteroids.length <= 10^4 2<=asteroids.length<=104
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

From: LeetCode
Link: 735. Asteroid Collision


Solution:

Ideas:

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.

Code:
/**
 * 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;
}
01-09 08:13