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
- 1 ≤ points.length ≤ 10⁵
- -2³¹ ≤ start < end ≤ 2³¹ − 1
- Compare with care: end − start can overflow a 32-bit int
Edge cases to test
- Touching balloons share an arrow:
[1, 2],[2, 3] - Nested balloons
- Large coordinates (sort comparator overflow in Java)
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³¹. UseInteger.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 arrowsC++
#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
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)