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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code