Destroying Asteroids (LeetCode 2126): Solution and Explanation

Medium
Array
Greedy
Sorting

A planet with mass mass collides with asteroids in any order you like. It destroys and absorbs each asteroid no heavier than itself, and is destroyed otherwise. Return whether it can destroy all of them.

Intuition

Every asteroid the planet destroys adds to its mass, and mass never goes down. So the planet only gets stronger as the game goes on.

That means there is never a reason to fight a heavy asteroid early. If the planet can beat a heavy rock now, it could also beat it later, after eating some light ones first. Smallest first is always at least as good as any other order.

Sort the asteroids and walk through them. If the planet ever meets a rock it cannot beat, every remaining rock is at least as heavy, so no order can save it and the answer is false.

Mass can grow to about 10^5 + 10^5 * 10^5, which is above 2^31, so keep it in a 64-bit integer.

Approach: Sort ascending and absorb greedily

  1. Sort asteroids in increasing order.
  2. Keep the planet's mass in a 64-bit variable.
  3. For each asteroid a, if mass < a return false.
  4. Otherwise add a to mass and continue.
  5. If the loop finishes, return true.

Step-by-step example

mass = 10, asteroids = [3,9,19,5,21]
  1. Sorted: [3, 5, 9, 19, 21].
  2. 10 >= 3, mass becomes 13. 13 >= 5, mass becomes 18.
  3. 18 >= 9, mass becomes 27.
  4. 27 >= 19, mass becomes 46. 46 >= 21, mass becomes 67.
  5. Every asteroid is destroyed, so return true.

Code: Python, Java, C++

1class Solution:
2    def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
3        asteroids.sort()
4        for a in asteroids:
5            if mass < a:
6                return False
7            mass += a
8        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort O(n + M)
Sort ascending and absorb greedily O(n log n)
Min-heap O(n log n)
Time

O(n log n)

Sorting dominates. The absorb loop is a single pass.

Space

O(1)

Only the running mass is kept, apart from the sort's own space.

Other approaches

Counting sort (time O(n + M), space O(M))

Asteroid masses are at most 10^5, so bucket them by mass and sweep the buckets upward. This removes the log factor at the cost of a 10^5 sized array.

Min-heap (time O(n log n), space O(n))

Push every asteroid into a min-heap and pop the lightest while the planet can beat it. It matches the greedy exactly but is slower than a plain sort in practice.

Common mistakes

  • Keeping the mass in a 32-bit int. With 10^5 asteroids of mass 10^5 the planet passes 2^31 and the value wraps around.
  • Using a strict comparison. The planet wins when its mass is greater than or equal to the asteroid's, so equal masses are fine.
  • Trying to be clever with the order, such as fighting the largest rock you can currently beat. Smallest first is never worse and is simpler.

Frequently asked questions

Why is smallest first optimal?

Mass only increases. If some order destroys every asteroid, then at each point the planet is at least as heavy under the sorted order as it would be facing the same rock in that order, so the sorted order succeeds too.

Can I return true early?

Yes. Once the mass is at least the largest asteroid, every remaining rock is beatable. It saves time on some inputs but does not change the worst case.

Why does the mass need 64 bits?

The final mass is the starting mass plus the sum of every asteroid, which can be around 10^10, well past the 32-bit limit of about 2.1 * 10^9.