Destroying Asteroids - Problem

Destroying Asteroids

You're given a planet with an initial mass and an array of asteroids where each asteroid has its own mass. The planet can collide with asteroids in any order you choose.

Collision Rules:

  • If planet_mass ≥ asteroid_mass: The asteroid is destroyed and the planet absorbs the asteroid's mass
  • If planet_mass < asteroid_mass: The planet is destroyed and the game ends

Your goal is to determine if there exists an order of collisions such that all asteroids can be destroyed.

Example: Planet mass = 10, asteroids = [3, 9, 19, 5, 21]
One winning strategy: destroy asteroids in order [3, 5, 9, 19, 21]
Mass progression: 10 → 13 → 18 → 27 → 46 → 67

Input & Output

example_1.py — Basic Success Case
$ Input: mass = 10, asteroids = [3, 9, 19, 5, 21]
Output: true
💡 Note: Sort to [3, 5, 9, 19, 21]. Planet can destroy all: 10→13→18→27→46→67. The greedy strategy works perfectly here.
example_2.py — Impossible Case
$ Input: mass = 5, asteroids = [4, 9, 23, 4]
Output: false
💡 Note: Sort to [4, 4, 9, 23]. Planet progresses: 5→9→13→22, but 22 < 23. Cannot destroy the largest asteroid.
example_3.py — Edge Case: Single Large Asteroid
$ Input: mass = 1, asteroids = [2]
Output: false
💡 Note: Planet mass 1 is less than asteroid mass 2. Planet gets destroyed immediately.

Constraints

  • 1 ≤ mass ≤ 105
  • 1 ≤ asteroids.length ≤ 105
  • 1 ≤ asteroids[i] ≤ 105
  • Important: Planet mass can grow beyond initial constraints after absorbing asteroids

Visualization

Tap to expand
🌍 Planet vs Asteroids: The Optimal Strategy🎯 Key Insight: Always fight the weakest enemy you can defeat!This greedy strategy maximizes your growth potential for future battles.Example: Planet Mass = 10, Asteroids = [3, 9, 19, 5, 21]Step 1: Sort asteroids → [3, 5, 9, 19, 21]10vs3→ 10+3=13 ✓13vs5→ 13+5=18 ✓18vs9→ 18+9=27 ✓27vs19→ 27+19=46 ✓46vs21→ 46+21=67 ✓🎉 ALL ASTEROIDS DESTROYED!Time Complexity: O(n log n)Dominated by sorting stepSpace Complexity: O(1)Only constant extra space needed
Understanding the Visualization
1
Sort enemies by strength
Arrange asteroids from weakest (smallest mass) to strongest (largest mass)
2
Fight in optimal order
Always challenge the weakest opponent you can currently defeat
3
Grow stronger with victories
Each victory adds the defeated asteroid's mass to your planet
4
Check if all can be defeated
If you can defeat every asteroid in this order, return true
Key Takeaway
🎯 Key Insight: The greedy approach works because destroying smaller asteroids first maximizes our future potential. This is a classic example of how local optimal choices lead to a globally optimal solution.
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
27.8K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen