-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0735-asteroid-collision.js
More file actions
43 lines (37 loc) · 1.19 KB
/
0735-asteroid-collision.js
File metadata and controls
43 lines (37 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Asteroid Collision
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var asteroidCollision = function (asteroids) {
const survivorsStack = [];
let currentAsteroidScanIndex = 0;
const totalAsteroidCount = asteroids.length;
while (currentAsteroidScanIndex < totalAsteroidCount) {
const currentIncomingAsteroid = asteroids[currentAsteroidScanIndex];
let didIncomingAsteroidExplode = false;
while (
survivorsStack.length > 0 &&
survivorsStack[survivorsStack.length - 1] > 0 &&
currentIncomingAsteroid < 0
) {
const stackTopAsteroid = survivorsStack[survivorsStack.length - 1];
const incomingAsteroidAbsoluteSize = Math.abs(currentIncomingAsteroid);
if (stackTopAsteroid === incomingAsteroidAbsoluteSize) {
survivorsStack.pop();
didIncomingAsteroidExplode = true;
break;
} else if (stackTopAsteroid < incomingAsteroidAbsoluteSize) {
survivorsStack.pop();
} else {
didIncomingAsteroidExplode = true;
break;
}
}
if (!didIncomingAsteroidExplode) {
survivorsStack.push(currentIncomingAsteroid);
}
currentAsteroidScanIndex++;
}
return survivorsStack;
};