#2126

Destroying Asteroids

Medium
ArrayGreedySortingGreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the asteroids and colliding with the smallest first, we ensure that we maximize the planet's mass gain at each step, which is a greedy approach.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the asteroids array in ascending order.
  2. 2Step 2: Initialize current_mass with the planet's mass.
  3. 3Step 3: Iterate through the sorted asteroids and check if current_mass is greater than or equal to the asteroid's mass.
  4. 4Step 4: If yes, add the asteroid's mass to current_mass. If no, return false.
  5. 5Step 5: If all asteroids are processed, return true.
solution.py11 lines
1# Full working Python code
2
3def canDestroyAsteroids(mass, asteroids):
4    asteroids.sort()
5    current_mass = mass
6    for asteroid in asteroids:
7        if current_mass >= asteroid:
8            current_mass += asteroid
9        else:
10            return False
11    return True

Complexity note: The time complexity is O(n log n) due to sorting the asteroids, and O(1) for space as we are modifying the input array in place.

  • 1Sorting the asteroids allows for a greedy approach to maximize mass gain.
  • 2If the planet cannot destroy an asteroid, it cannot destroy any larger asteroid.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.