Destroying Asteroids — LeetCode 2126 Python Solution
- Problem
- #2126
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- mass = 10, asteroids = [3,9,19,5,21]
- Output
- true
- Explanation
- One way to order the asteroids is [9,19,5,3,21]:
Python solution
class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for x in asteroids:
if mass < x:
return False
mass += x
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2126. Destroying Asteroids is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2126. Destroying Asteroids?
- LeetCode 2126. Destroying Asteroids is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2126. Destroying Asteroids?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2126. Destroying Asteroids?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2126. Destroying Asteroids cover?
- LeetCode 2126. Destroying Asteroids is tagged Greedy, Array and Sorting on LeetCode.