< Back




2126. Destroying Asteroids

Classic example of a greedy problem. The planet absorbs asteroids with mass less than or equal to its
own mass. We have to prove if we can absorb all asteroids - won't happen if we encounter a large
asteroid first. If we sort the asteroids in ascending order, we can just iterate through them and
absorb them one by one. If we encounter an asteroid that's too large, we can't absorb it and we
return False.

The solution is as follows:


class Solution:
    def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
        asteroids.sort()

        for asteroid in asteroids:
            if asteroid > mass:
                return False
            mass += asteroid
        
        return True


_ Time Complexity:

  O(n log(n)) - We have to sort the asteroids.

_ Space Complexity:

  O(n) - Python sorting uses O(n) space.