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.
{
"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.
{
"asteroids": [1, 13, 8, -8, -5, 5, -5, -11]
}
Output:
[1, 13]
{
"asteroids": [-13, 8]
}
Output:
[-13, 8]
Constraints:
"""
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
"""
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
/*
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.
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.
{
"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.
{
"asteroids": [1, 13, 8, -8, -5, 5, -5, -11]
}
Output:
[1, 13]
{
"asteroids": [-13, 8]
}
Output:
[-13, 8]
Constraints:
"""
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
"""
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
/*
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.
Attend our free webinar to amp up your career and get the salary you deserve.