452. Minimum Number of Arrows to Burst Balloons
Problem
Balloons are horizontal ranges [xstart, xend]. An arrow shot straight up at x bursts every balloon with xstart ≤ x ≤ xend. Return the minimum number of arrows needed to burst them all.
Example: [[10,16],[2,8],[1,6],[7,12]] → 2 (shoot at x = 6 and x = 11)
Constraints: up to 10⁵ balloons; coordinates span the full 32-bit range.
Sort by end; shoot at the first end. Every balloon starting ≤ that point is burst; the next balloon starting after it needs a new arrow at its end.
Complexity: O(n log n).
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
arrows, pos = 0, float("-inf")
for s, e in sorted(points, key=lambda p: p[1]):
if s > pos:
arrows += 1
pos = e
return arrows
assert Solution().findMinArrowShots([[10, 16], [2, 8], [1, 6], [7, 12]]) == 2
assert Solution().findMinArrowShots([[1, 2], [3, 4], [5, 6], [7, 8]]) == 4
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); // compare() avoids overflow
int arrows = 0;
long pos = Long.MIN_VALUE;
for (int[] p : points) if (p[0] > pos) { arrows++; pos = p[1]; }
return arrows;
}
}
func findMinArrowShots(points [][]int) int {
sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] })
arrows, pos := 0, math.MinInt
for _, p := range points { // shoot at the end of the first balloon not yet burst
if p[0] > pos {
arrows++
pos = p[1]
}
}
return arrows
}