#2126
Medium Algorithms Destroying asteroids
Array Greedy Sorting
53.3% acceptance
Feb 25, 2026
595
198
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn asteroids_destroyed(mass: i32, asteroids: Vec<i32>) -> bool {
let mut asteroids = asteroids;
asteroids.sort();
let mut mass = mass as i64;
for a in asteroids {
if mass < a as i64 {
return false;
}
mass += a as i64;
}
true
}
}