sagelearnai

Minimum Number of Arrows to Burst Balloons

Difficulty: Medium · Pattern: Intervals · LeetCode #452

Each balloon spans a horizontal range [xstart, xend]. A vertical arrow shot at position x bursts every balloon with xstart ≤ x ≤ xend (touching counts). Return the minimum number of arrows needed to burst all balloons.

Examples

text
points = [[10, 16], [2, 8], [1, 6], [7, 12]]   →  2    (shoot at 6 and 12)
points = [[1, 2], [3, 4], [5, 6], [7, 8]]      →  4
points = [[1, 2], [2, 3], [3, 4], [4, 5]]      →  2    (shoot at 2 and 4)

Hints

  1. Look at the balloon that ends first. Some arrow must hit it, and shooting at its end hits as many other balloons as possible.
  2. Sort by end, then count how many times you need a new arrow.

Approach

Sort by end. Shoot the first arrow at the end of the first balloon. For each subsequent balloon, if its start ≤ the current arrow position, it's already burst; otherwise shoot a new arrow at its end. Same exchange argument as interval scheduling. Note that touching counts here, hence > for the "new arrow" test.

Complexity

Time: O(n log n). Space: O(1) extra.

Python solution
def findMinArrowShots(points):
    points.sort(key=lambda p: p[1])
    arrows, pos = 0, float('-inf')
    for s, e in points:
        if s > pos:
            arrows += 1
            pos = e
    return arrows
JavaScript solution
function findMinArrowShots(points) {
  points.sort((a, b) => a[1] - b[1]);
  let arrows = 0, pos = -Infinity;
  for (const [s, e] of points) if (s > pos) { arrows++; pos = e; }
  return arrows;
}