Minimum Number of Arrows to Burst Balloons

MediumGreedyLeetCode 452 ↗World 7-12
0:00 / 0:00

Sort balloons by where they end and shoot each arrow at the earliest end. It pops every balloon still overlapping it, so you need the fewest.

▼

The problem

LeetCode 452 (Medium). Balloons are horizontal intervals [xstart, xend] on a wall. An arrow shot straight up at x bursts every balloon with xstart <= x <= xend (ends included). Return the minimum number of arrows that burst them all.

Example (LeetCode's first): [[10,16],[2,8],[1,6],[7,12]] → 2 (arrows at 6 and 12; one arrow can't do it, since [1,6] and [10,16] don't overlap).

TRY IT ON LEETCODE ▶

The solution

def find_min_arrow_shots(points):
    points.sort(key=lambda b: b[1])   # by end
    arrows, x = 1, points[0][1]       # first arrow
    for s, e in points[1:]:
        if s > x:                     # untouched
            arrows += 1
            x = e                     # new arrow at its end
        # else: already burst
    return arrows

Transcript

Minimum Number of Arrows to Burst Balloons. Long balloons are pinned across a wall, each from a start to an end. An archer shoots arrows straight up. An arrow at x bursts every balloon covering x, ends included. What's the fewest arrows that burst them all?

LeetCode's first example: ten to sixteen, two to eight, one to six, and seven to twelve. An arrow at six bursts one to six and two to eight. An arrow at twelve bursts the other two. Two arrows do it, and one can't: one to six and ten to sixteen never meet.

A first guess: shoot where the most balloons overlap, then repeat. Finding that spot checks every end against every balloon, n squared work per arrow. Worse, it can waste arrows. Here the busiest spot bursts four, but the two leftovers sit far apart: three arrows, when two would do.

Instead, look at the balloon that ends first. Some arrow has to burst it, somewhere between its start and end. Sliding that arrow right, to the balloon's end, only helps: every balloon started by then gets burst too. So sort by end, and shoot at the first end.

In code, sort by end. The first arrow goes at the first end, and the count is one. For each next balloon, if it starts after the arrow, it's untouched: add an arrow at its end. Otherwise, it's already burst. Return the count.

Let's run the first example. Sorted by end: one to six, two to eight, seven to twelve, ten to sixteen. Arrow one flies at six. Two to eight starts before six: already burst. Seven to twelve starts after six, so arrow two flies at twelve. Ten to sixteen starts before twelve: burst. Two arrows.

Sorting takes n log n time, and the pass after it is linear. Beyond the sort, we keep just the arrow's spot and a count, so the extra space is constant.

Sort by end, shoot at the first end, skip what's already burst. That's Minimum Number of Arrows to Burst Balloons.