Leetcode 2126: Destroying Asteroids

grid47
grid47
Exploring patterns and algorithms
Apr 8, 2024 6 min read

You are given a planet with an initial mass. There are asteroids approaching the planet, each with its own mass. The planet can destroy an asteroid if its current mass is greater than or equal to the asteroid’s mass. After destroying an asteroid, the planet’s mass increases by the asteroid’s mass. You need to determine if the planet can destroy all the asteroids by strategically choosing the order of the collisions.
Problem
Approach
Steps
Complexity
Input: You are given an integer representing the planet's mass and an array of integers representing the mass of each asteroid.
Example: mass = 15, asteroids = [7, 4, 9, 3, 2]
Constraints:
• 1 <= mass <= 10^5
• 1 <= asteroids.length <= 10^5
• 1 <= asteroids[i] <= 10^5
Output: Return true if all the asteroids can be destroyed, otherwise return false.
Example: Input: mass = 15, asteroids = [7, 4, 9, 3, 2] Output: true
Constraints:
• The mass of the planet and asteroids is within the specified range.
Goal: To determine if the planet can destroy all the asteroids, we need to check if the planet's mass is sufficient for each asteroid as we go through the list.
Steps:
• Sort the asteroids in ascending order.
• Iterate over each asteroid and check if the planet's current mass is greater than or equal to the asteroid's mass.
• If the planet can destroy the asteroid, increase the planet's mass by the asteroid's mass.
• If at any point the planet cannot destroy an asteroid, return false.
Goal: Ensure that the solution handles large input sizes efficiently.
Steps:
• The number of asteroids can be as large as 10^5.
• The mass of the planet and asteroids can be as large as 10^5.
Assumptions:
• The asteroids are processed in a way that allows the planet to destroy them in the most efficient order.
Input: Input: mass = 15, asteroids = [7, 4, 9, 3, 2]
Explanation: The planet starts with a mass of 15. By sorting the asteroids, the planet can destroy them in the order [2, 3, 4, 7, 9]. After destroying all asteroids, the planet's mass will be 15 + 2 + 3 + 4 + 7 + 9 = 40. Since the planet can destroy all asteroids, the output is true.

Input: Input: mass = 10, asteroids = [4, 9, 8, 6]
Explanation: The planet starts with a mass of 10. By sorting the asteroids, the planet can destroy them in the order [4, 6, 8]. However, after destroying the asteroid with mass 8, the planet's mass is still only 18, which is not enough to destroy the asteroid with mass 9. Therefore, the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus