LeetCode 2126: Destroying Asteroids Solution
Master LeetCode problem 2126 (Destroying Asteroids), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can simulate the process of colliding asteroids with the planet. We can use a priority queue to maintain the order of asteroids based on their mass. We start by adding all the asteroids to the priority queue. Then, we iterate through the priority queue and simulate the collisions with the planet. If at any point the planet's mass is less than an asteroid's mass, we return false. If we successfully process all asteroids, we return true.
Algorithm:
- Create a priority queue to store asteroids based on their mass.
- Add all asteroids to the priority queue.
- Initialize the planet's mass to the given initial mass.
- Iterate through the priority queue:
- If the planet's mass is greater than or equal to the current asteroid's mass, destroy the asteroid and update the planet's mass.
- If the planet's mass is less than the current asteroid's mass, return false.
- If all asteroids are successfully destroyed, return true.
Time Complexity:
The time complexity of this algorithm is O(n log n), where n is the number of asteroids.
Space Complexity:
The space complexity is O(n) to store the priority queue.
:
Solution Code
import java.util.PriorityQueue;
class Solution {
public boolean canDestroyAsteroids(int mass, int[] asteroids) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for (int asteroid : asteroids) {
pq.offer(asteroid);
}
while (!pq.isEmpty()) {
int currentAsteroid = pq.poll();
if (mass >= currentAsteroid) {
mass += currentAsteroid;
} else {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2126 (Destroying Asteroids)?
This page provides optimized solutions for LeetCode problem 2126 (Destroying Asteroids) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2126 (Destroying Asteroids)?
The time complexity for LeetCode 2126 (Destroying Asteroids) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2126 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2126 in Java, C++, or Python.