Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding state after all collisions in JavaScript
Problem
We are required to write a JavaScript function that takes in an array, arr, that represents the positions of different asteroids in a one-dimensional 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.
Our function is supposed to 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 Input and Output
For example, if the input to the function is:
const arr = [7, 12, -8];
Expected Output:
[7, 12]
Output Explanation: The 12 and -8 will collide resulting in 12. The 7 and 12 will never collide since they're both moving right.
Algorithm
The solution uses a stack-based approach to simulate asteroid collisions. We iterate through each asteroid and use a tracking array to handle collisions between right-moving and left-moving asteroids.
Solution
const arr = [7, 12, -8];
const findState = (arr = []) => {
const track = [];
for (const el of arr) {
track.push(el);
// Check for collision: last is negative (left), second-to-last is positive (right)
while (track.length >= 2 &&
track[track.length - 1] < 0 &&
track[track.length - 2] > 0) {
const leftMoving = -track.pop(); // Convert to positive for size comparison
const rightMoving = track.pop();
if (leftMoving > rightMoving) {
// Left asteroid survives
track.push(-leftMoving);
} else if (leftMoving < rightMoving) {
// Right asteroid survives
track.push(rightMoving);
}
// If equal, both explode (do nothing)
}
}
return track;
};
console.log(findState(arr));
console.log(findState([5, 10, -5]));
console.log(findState([8, -8]));
console.log(findState([10, 2, -5]));
[7, 12] [5, 10] [] [10]
How It Works
The algorithm processes each asteroid sequentially:
- Add each asteroid to the tracking stack
- After adding, check if collision occurs (positive followed by negative)
- Compare sizes and keep the larger asteroid, or remove both if equal
- Continue until no more collisions are possible
Key Points
- Only asteroids moving in opposite directions can collide
- Collisions happen when a right-moving asteroid meets a left-moving one
- The stack approach efficiently handles chain reactions of collisions
- Time complexity: O(n), Space complexity: O(n)
Conclusion
This solution efficiently simulates asteroid collisions using a stack-based approach. The algorithm handles all collision scenarios including chain reactions, making it optimal for solving the asteroid collision problem.
