Destroying Asteroids - Problem
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.
You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.
Return true if all asteroids can be destroyed. Otherwise, return false.
Input & Output
Example 1 — Basic Success
$
Input:
mass = 10, asteroids = [3,9,19,5,21]
›
Output:
true
💡 Note:
Sort to [3,5,9,19,21]. Planet: 10→13→18→27→46→67. All asteroids destroyed successfully.
Example 2 — Impossible Case
$
Input:
mass = 5, asteroids = [4,9,23,4]
›
Output:
false
💡 Note:
Sort to [4,4,9,23]. Planet: 5→9→13→22. Cannot destroy asteroid 23 (mass 22 < 23).
Example 3 — Edge Case
$
Input:
mass = 10, asteroids = []
›
Output:
true
💡 Note:
No asteroids to destroy, so automatically return true.
Constraints
- 1 ≤ mass ≤ 105
- 1 ≤ asteroids.length ≤ 105
- 1 ≤ asteroids[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Planet with initial mass and array of asteroid masses
2
Strategy
Sort asteroids and attack smallest first to maximize growth
3
Result
Return whether all asteroids can be destroyed
Key Takeaway
🎯 Key Insight: Always attack the smallest asteroid you can handle to maximize mass growth and future opportunities
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code