Register for our webinar

### How to Nail your next Technical Interview

1 hour
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
Step 1
Step 2
Congratulations!
You have registered for our webinar
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

## You may be missing out on a 66.5% salary hike*

### Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Help us know you better!

## How many years of coding experience do you have?

Oops! Something went wrong while submitting the form.

## FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Oops! Something went wrong while submitting the form.

# 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
"""
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:

### Try yourself in the Editor

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

# 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
"""
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: