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 - Greedy Approach INPUT Planet mass = 10 Asteroids Array: 3 9 19 5 21 [0] [1] [2] [3] [4] Unsorted asteroids Need to destroy all! ALGORITHM STEPS 1 Sort Ascending [3, 5, 9, 19, 21] 2 Process Each Start with smallest 3 Check mass >= asteroid Absorb if possible 4 Update mass mass += asteroid Simulation: 10 >= 3 [OK] mass=13 13 >= 5 [OK] mass=18 18 >= 9 [OK] mass=27 27 >= 19 [OK] mass=46 46 >= 21 [OK] mass=67 All destroyed! FINAL RESULT OK SUCCESS Output: true Planet Growth: 10 13 27 46 67 FINAL Key Insight: By sorting asteroids in ascending order, we maximize our chances of success. Starting with smaller asteroids allows the planet to grow gradually. Each absorbed asteroid increases our mass, making it easier to absorb larger ones. Greedy choice: always pick the smallest available asteroid next. TutorialsPoint - Destroying Asteroids | Greedy - Sort Ascending
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