Asteroid Collision Problem

Asteroid Collision Problem Statement

Given a list of numbers 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 One

{
"asteroids": [13, 8, -8, 5, 5, -5, -11]
}

Output:

[13]

The 8, -8 and 5, -5 pairs collide exploding each others. That remains with astroids [13, 5, -11].
Then 5 and -11 collide resulting in -11, which gets destroyed by 13 later.
Thus only the 13 remains.

Example Two

{
"asteroids": [1, 13, 8, -8, -5, 5, -5, -11]
}

Output:

[1, 13]

Example Three

{
"asteroids": [-13, 8]
}

Output:

[-13, 8]

Notes

Constraints:

  • 1 <= size of the input list <= 105
  • -103 <= any element of the input list <= 103
  • any element of the input list != 0

Code For Asteroid Collision Solution 1: Brute Force.P


"""
Asymptotic complexity in terms of the size of the input list `n`:
* Time: O(n ^ 2).
* Auxiliary space: O(1).
* Total space: O(n).
"""

def asteroid_collision(asteroids):
    i = 0
    while i < len(asteroids) - 1:
        if asteroids[i] > 0 and asteroids[i+1] < 0: # If there is a collision
            if asteroids[i] > -asteroids[i+1]:
                del asteroids[i+1] # asteroid i+1 gets destroyed
            elif asteroids[i] < -asteroids[i+1]:
                del asteroids[i] # asteroid i gets destroyed
                i = max(0, i-1) # Move back one step to handle possible continuous collisions
            else:
                del asteroids[i:i+2] # Both get destroyed
                i = max(0, i-1) # Move back one step to handle possible continuous collisions
        else:
            i += 1
    return asteroids

Code For Asteroid Collision Solution 2: Stack


"""
Asymptotic complexity in terms of the size of the input list `n`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""

def asteroid_collision(asteroids):
    """
    Args:
     asteroids(list_int32)
    Returns:
     list_int32
    """
    # Write your code here.
    stack = []
    for a in asteroids:
        if a > 0:
            stack.append(a)
        else:
            destroyed = False
            while stack and stack[-1] > 0:
                if stack[-1] > -a:
                    destroyed = True
                    break
                elif stack[-1] == -a:
                    destroyed = True
                    stack.pop()
                    break
                else:
                    stack.pop()
            if not destroyed:
                stack.append(a)

    return stack

Code For Asteroid Collision Solution 3: Stack

/*
Asymptotic complexity in terms of the size of the input list `n`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

vector<int> asteroid_collision(vector<int> &asteroids) {
    // Use vectoring to simulate stack.
    vector<int> s;
    for (int i = 0; i < asteroids.size(); i++) {
        // When `asteroids[i]` is positive or `asteroids[i]` is negative and there is no positive on stack.
        if (s.empty() || asteroids[i] > 0 || s.back() < 0) {
            s.push_back(asteroids[i]);
        }
        // When `asteroids[i]` is negative and stack top is positive and negetive star is bigger or equal than the positive star.
        else if (s.back() <= -asteroids[i]) {
            // Only the positive star on stack top gets destroyed, staying on i to check more on stack.
            if(s.back() < -asteroids[i]) {
                i--;
            }
            // Destroy positive star on the frontier.
            s.pop_back();
        }
        // Otherwise, positive on stack bigger, negative star destroyed. Do nothing.
    }
    return s;
}

We hope that these solutions to the asteriod collision problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Binary Tree Level Order Traversal Problem with Examples

Jump Game

Zigzag Sort Problem

Boggle Solver Problem

Shortest String Transformation Using A Dictionary Problem

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC