The problem. You're given an array asteroids of non-zero integers in a row. The absolute value is an asteroid's size; the sign is its direction — positive moves right, negative moves left. All move at the same speed. When two meet, the smaller one explodes; if they're the same size, both explode. Asteroids moving the same way never meet. Return the asteroids left after all collisions.
Input: [5, 10, -5] Output: [5, 10] -5 hits 10 and explodes
Input: [8, -8] Output: [] same size: both explode
Input: [10, 2, -5] Output: [10] -5 destroys 2, then hits 10 and explodes
Input: [-2, -1, 1, 2] Output: [-2, -1, 1, 2] left-movers on the left never meet right-moversA collision needs a right-mover followed by a left-mover. And when a left-mover destroys an asteroid, it keeps going and meets the next survivor to its left — the newest item reacting with the latest survivor, then the one before that. That's the stack signal.
Free account
Sign up to read the rest of this lesson: 5 more sections, 3 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come