Algo-Sim › Greedy

Minimum Number of Arrows to Burst Balloons

Medium · Greedy · step through it in Java, Python and C++ on your own input

Each balloon spans [start, end]; an arrow at x bursts every balloon covering x. Sort by end and shoot at the end of the first balloon not yet burst.

Problem

Balloons hang along the x-axis, balloon i covering [start, end] inclusive. An arrow shot straight up at position x bursts every balloon with start ≤ x ≤ end. Return the fewest arrows needed to burst all balloons.

Constraints

Edge cases to test

Follow-up questions

Why sort by end?
Shooting at the earliest end bursts that balloon and as many others as any position could: the interval-scheduling exchange argument.
Why can a comparator overflow?
a[1] − b[1] overflows for values near ±2³¹. Use Integer.compare(a[1], b[1]).

Solution

Java

public int findMinArrowShots(int[][] points) {
    Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1]));
    int arrows = 1, arrow = points[0][1];
    for (int i = 1; i < points.length; i++) {
        if (points[i][0] <= arrow) continue;
        arrows++;
        arrow = points[i][1];
    }
    return arrows;
}

Python

def find_min_arrow_shots(points):
    points.sort(key=lambda p: p[1])
    arrows, arrow = 1, points[0][1]
    for start, end in points[1:]:
        if start <= arrow:
            continue
        arrows += 1
        arrow = end
    return arrows

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findMinArrowShots(vector<vector<int>> &points) {
        sort(points.begin(), points.end(), [](const auto &a, const auto &b) { return a[1] < b[1]; });
        int arrows = 1, arrow = points[0][1];
        for (int i = 1; i < int(points.size()); i++) {
            if (points[i][0] <= arrow)
                continue;
            arrows++;
            arrow = points[i][1];
        }
        return arrows;
    }
};

More Greedy problems