Minimum Number of Arrows to Burst Balloons

Medium

Topics
ArrayGreedySortingIntervals

There are some spherical balloons taped onto a flat wall. The balloons are given as a 2D array points where points[i] = [xstart, xend] is the horizontal span of the i-th balloon.

Arrows are shot vertically upward from a point x on the x-axis. A balloon with span [xstart, xend] is burst if xstart <= x <= xend. An arrow travels infinitely upward, bursting every balloon it passes through.

Return the minimum number of arrows that must be shot to burst all balloons. On this judge the array is passed as a grid with two columns.

Example 1

116[10,16][2,8][1,6][7,12]arrows
An arrow at coordinate x bursts every balloon whose span covers x. Firing at the earliest end point among the balloons still alive bursts as many as possible, so the 2 arrows marked below the axis (at x = 6, 12) clear all 4.
Each lane is one interval drawn on a shared axis, so overlaps line up vertically.
Input:  grid = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: Shoot at x = 6 to burst [2,8] and [1,6], then at x = 11 to burst [10,16] and [7,12].

Example 2

18[1,2][3,4][5,6][7,8]arrows
Firing at the earliest end point among the balloons still alive bursts as many as possible, so the 4 arrows marked below the axis (at x = 2, 4, 6, 8) clear all 4.
Input:  grid = [[1,2],[3,4],[5,6],[7,8]]
Output: 4

Example 3

15[1,2][2,3][3,4][4,5]arrows
Input:  grid = [[1,2],[2,3],[3,4],[4,5]]
Output: 2

Constraints

  • 1 <= points.length <= 10^5
  • points[i].length == 2
  • -2^31 <= xstart < xend <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

An arrow should never be wasted, so every arrow you shoot should burst as many balloons as it possibly can. Sort by right endpoint and always shoot at the smallest right endpoint still unburst. That position is the last chance to hit that balloon, so it is the position that keeps the most future balloons in range - no other choice can do better, which is the exchange argument that makes greedy correct here.

Approach

  1. Sort the balloons by their end coordinate ascending.
  2. Shoot the first arrow at the first balloon's end. Set arrows = 1 and remember that position.
  3. Walk the rest. If a balloon's start is <= the current arrow position, it is already burst - skip it.
  4. Otherwise it is out of range: shoot a new arrow at this balloon's end and update the position.
class Solution:
    def findMinArrowShots(self, grid):
        grid.sort(key=lambda p: p[1])
        arrows = 1
        pos = grid[0][1]
        for start, end in grid[1:]:
            if start > pos:
                arrows += 1
                pos = end
        return arrows

Dry Run

balloons [[10,16], [2,8], [1,6], [7,12]]
  sorted by end:  [1,6] [2,8] [7,12] [10,16]
  first arrow at x = 6, the earliest end
  [2,8]    starts at 2  <= 6   the same arrow pops it
  [7,12]   starts at 7  >  6   out of reach, NEW arrow at x = 12
  [10,16]  starts at 10 <= 12  the second arrow pops it too
answer 2
Shooting at the earliest end is the greedy choice, and it is optimal because any
arrow that pops the earliest-ending balloon must land at or before that end --
placing it exactly there can only pop more, never fewer.
Sorting by end rather than start is load-bearing, even though this input returns 2
either way. [[1,10],[2,3],[4,5]] separates them: the answer is 2, and sorting by
start returns 1, because the greedy anchors on the huge [1,10] and then believes
one arrow covers everything nested inside it.
Touching counts as bursting, so the reach test is `start > shot` -- non-strict in
the other direction. With `start >= shot`, [[1,2],[2,3]] needs 2 arrows where one
at x = 2 pops both.
In Java and C++, writing the comparator as `a[1] - b[1]` overflows at the extreme
constraint values. Compare, do not subtract.

Complexity

  • Time — O(n log n) — dominated by the sort; the sweep is linear.
  • Space — O(n) in Java and Python, O(log n) in C++: the sweep tracks one arrow position, so O(1) of its own, and the sort is everything else. It is the object-sort case rather than the cheaper primitive one: sorting int[][] through a comparator uses Timsort in both Java and Python, which allocates an O(n) merge buffer, whereas C++ std::sort is in place and costs O(log n) of recursion.

Common Pitfalls

  • Sort by end, not by start. Sorting by start gives wrong answers on nested intervals, though not on this page's input, which returns 2 either way. [[1,10],[2,3],[4,5]] separates them: the answer is 2 and sorting by start returns 1, because the greedy anchors on [1,10] and assumes one arrow covers everything nested in it.
  • Touching counts as bursting: start <= pos uses a non-strict comparison, so [1,2] and [2,3] need only one arrow.
  • In Java and C++, writing the comparator as a[1] - b[1] overflows on the extreme constraint values. Compare, do not subtract.
  • This is the same exchange argument as Non-Overlapping Intervals - solve both and the pattern locks in.

Full Solution — all languages

class Solution:
    def findMinArrowShots(self, grid):
        if not grid:
            return 0
        balloons = sorted(grid, key=lambda p: p[1])
        arrows = 1
        shot = balloons[0][1]
        for start, end in balloons[1:]:
            if start > shot:
                arrows += 1
                shot = end
        return arrows
SensAI
Beta
Tap the mic to stop voice mode