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
Destroying Asteroids: Strategic Growth10PlanetAsteroids: [5, 10, 4]5104AttackOptimal Order: [4, 5, 10]4510Sorted by sizeGrowth Sequence:Mass 10 + Asteroid 4 → Mass 14Mass 14 + Asteroid 5 → Mass 19Mass 19 + Asteroid 10 → Mass 2929Final MassResult: true - All asteroids destroyed!
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
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K 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