Taro Logo

Asteroid Collision

#2 Most AskedMedium
0 views
Topics:
ArraysStacks

We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod 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.

Constraints:

  • 2 <= asteroids.length <= 104
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can an asteroid have a size of zero, or will all integer values be strictly non-zero?
  2. What should be returned if all asteroids explode and no asteroids are left?
  3. How should we handle asteroids moving in the same direction (e.g., both positive or both negative)? Do they ever collide?
  4. Are the input values guaranteed to fit within standard 32-bit signed integers?
  5. If multiple asteroids of equal size collide simultaneously, do they all destroy each other, or does the collision order matter?

Brute Force Solution

Approach

Imagine a straight line where space rocks are moving toward or away from each other. The brute force strategy involves repeatedly letting every rock take one step forward in its preferred direction, pausing to check if any two rocks crash into each other.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire line of space rocks as they currently stand.
  2. Simulate the movement of all rocks forward by a tiny amount of distance at the same time.
  3. Check if any rock moving to the right has collided with a rock moving to the left right in front of it.
  4. If a collision happens, compare their sizes to see which one destroys the other or if they both disappear.
  5. If a rock is destroyed, remove it from the line immediately.
  6. Repeat the moving, checking, and destroying process over and over again from the very beginning of the line.
  7. Keep doing this until all the rocks have either destroyed each other or moved away so far that they will never meet again.

Code Implementation

def asteroid_collision(asteroids):
    current_index = 0
    
    # We repeatedly scan from the beginning because a collision can cascade backwards
    while current_index < len(asteroids) - 1:
        current_rock = asteroids[current_index]
        next_rock = asteroids[current_index + 1]
        
        # A collision occurs only when a right-moving rock meets a left-moving rock
        if current_rock > 0 and next_rock < 0:
            if abs(current_rock) == abs(next_rock):
                asteroids.pop(current_index + 1)
                asteroids.pop(current_index)
                current_index = max(0, current_index - 1)
            elif abs(current_rock) < abs(next_rock):
                asteroids.pop(current_index)
                current_index = max(0, current_index - 1)
            else:
                asteroids.pop(current_index + 1)
        else:
            current_index += 1
            
    return asteroids

Big(O) Analysis

Time Complexity
O(n²) – In this simulation strategy, we repeatedly scan through the entire array of n asteroids to move them and check for collisions. Because a single collision can require restarting the scan from the beginning, we might need to perform these full sweeps multiple times. In the worst-case scenario where many rocks interact, we iterate through n elements for up to n times. This gives us approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(N) – To simulate the collisions and keep track of the surviving rocks, the algorithm utilizes an auxiliary stack data structure. In the worst-case scenario where no rocks collide, all N asteroids are pushed onto this stack. Therefore, the extra memory required scales linearly with the input size N, leading to a space complexity of O(N).

Optimal Solution

Approach

The optimal strategy is to process the space objects one by one from left to right, keeping track of the survivors as you go. When a new object traveling left meets an object traveling right, they clash and the heavier one destroys the lighter one.

Here's how the algorithm would work step-by-step:

  1. Imagine a single file line where space objects are moving either to the left or to the right.
  2. As you encounter each space object in order, consider what is currently traveling directly in front of it.
  3. If a newly arriving object is traveling to the left and runs into an object traveling to the right, they clash.
  4. Compare the sizes of the two clashing objects.
  5. If the object traveling right is bigger, the new object is destroyed and vanishes.
  6. If the new object traveling left is bigger, the right-moving object is destroyed, and the new object keeps moving left to face whatever is next in line.
  7. If they are the exact same size, both objects destroy each other completely.
  8. If there is no clash because they are moving away from each other or both moving the same direction, simply add the new object to the ongoing line of survivors.
  9. Continue this process for all objects until everyone has moved through the system, leaving only the final survivors.

Code Implementation

def asteroidCollision(asteroid_list):
    surviving_asteroids = []

    for current_asteroid in asteroid_list:
        # Collisions only occur when a right-moving object meets a left-moving object.
        while surviving_asteroids and current_asteroid < 0 and surviving_asteroids[-1] > 0:
            previous_asteroid = surviving_asteroids[-1]
            
            if abs(previous_asteroid) < abs(current_asteroid):
                surviving_asteroids.pop()
                continue
            elif abs(previous_asteroid) == abs(current_asteroid):
                surviving_asteroids.pop()
            
            # If the surviving object is larger, the incoming object is destroyed.
            break
        else:
            surviving_asteroids.append(current_asteroid)

    return surviving_asteroids

Big(O) Analysis

Time Complexity
O(n) – In this simulation, we iterate through the array of n asteroids exactly once using a single main loop. As we process each asteroid, a stack keeps track of the surviving asteroids, and any colliding elements are popped from the stack. Each individual asteroid is pushed onto the stack at most once and popped from the stack at most once during the entire process. This means the total number of inner comparison operations across the entire run is bounded linearly rather than repeating fully for every element. Therefore, the total operations scale directly proportional to the input size n, simplifying to O(n).
Space Complexity
O(N) – To keep track of the survivors as you go through the space objects, an auxiliary stack or dynamic array is used to store the remaining elements. In the worst-case scenario where no collisions occur and all objects move in the same direction, this stack will hold all N objects. As the input size N grows, the memory consumed by this survivor list scales linearly. Therefore, the auxiliary space complexity simplifies to Big O of N.

Edge Cases

Empty or null input array
How to Handle:
Return the empty array immediately without processing since no collisions can occur.
Single element input array
How to Handle:
Return the array as is because a single asteroid cannot collide with anything.
All asteroids moving in the same direction (all positive or all negative)
How to Handle:
The stack will accumulate all elements without any collisions occurring, returning the original array.
Asteroids moving away from each other (negative followed by positive)
How to Handle:
The stack preserves both elements since their trajectories diverge and they never meet.
Chain reaction collisions where a newly exposed asteroid destroys subsequent incoming ones
How to Handle:
A while loop checking the stack ensures the current asteroid is continuously compared against all previous colliding elements.
Asteroids of identical absolute sizes colliding
How to Handle:
Both asteroids destroy each other by popping the stack and preventing the current asteroid from being added.
Extremely large input size requiring linear time complexity
How to Handle:
Using a stack data structure ensures each asteroid is pushed and popped at most once, achieving efficient O(N) time complexity.
Maximum possible integer values representing asteroid sizes
How to Handle:
Standard integer comparisons are used safely without risk of overflow since we only compare magnitudes directly.
0/5 completed