Asteroid Collision LeetCode solution in JavaScript

1
/**
2
* @param {number[]} asteroids
3
* @return {number[]}
4
*/
5
var asteroidCollision = function (asteroids) {
6
const s = [];
7
for (let i = 0; i < asteroids.length; i++) {
8
const a = asteroids[i];
9

10
// Negative asteroids to the left of the stack can be ignored.
11
// They'll never collide. Let's just add it to the answer stack and
12
// move on. I consider this a special case.
13
if ((s.length === 0 || s[s.length - 1] < 0) && a < 0) {
14
s.push(a);
15

16
// If an asteroid a is positive (l to r), it may still collide with an
17
// a negative asteroid further on in the asteroids array
18
} else if (a > 0) {
19
s.push(a);
20

21
// a is negative. It can only collide with positive ones in
22
// the stack. The following will keep on iterating
23
// until it is dealt with.
24
} else {
25
const pop = s.pop();
26

27
// positive pop beats negative a, so pick up pop
28
// and re-add it to the stack.
29
if (Math.abs(pop) > Math.abs(a)) {
30
s.push(pop);
31

32
// a has larger size than pop, so pop will get dropped
33
// and we'll retry another iteration with the same
34
// negative a asteroid and whatever the stack's state is.
35
} else if (Math.abs(pop) < Math.abs(a)) {
36
i--;
37
// magnitude of positive pop and negative a are the same
38
// so we can drop both of them.
39
} else {
40
continue;
41
}
42
}
43
}
44

45
// The stack should be the answer
46
return s;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0