Minimum Number of Arrows to Burst Balloons — LeetCode 452 Python Solution

MediumGreedyArraySorting
Problem
#452
Pattern
Greedy
Reading time
2 min

The problem

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend.

Example

Input
points = [[10,16],[2,8],[1,6],[7,12]]
Output
2
Explanation
The balloons can be burst by 2 arrows:

Python solution

Python
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        ans, last = 0, -inf
        for a, b in sorted(points, key=lambda x: x[1]):
            if a > last:
                ans += 1
                last = b
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 452. Minimum Number of Arrows to Burst Balloons 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

On study lists

This problem is on LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 452. Minimum Number of Arrows to Burst Balloons?
LeetCode 452. Minimum Number of Arrows to Burst Balloons is rated Medium on LeetCode.
What topics does LeetCode 452. Minimum Number of Arrows to Burst Balloons cover?
LeetCode 452. Minimum Number of Arrows to Burst Balloons is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview