class Solution:
def findMinArrowShots(self, points):
if not points:
return 0
# Sort balloons by their ending x coordinate
points.sort(key=lambda x: x[1])
arrows = 1
end = points[0][1]
for x_start, x_end in points[1:]:
if x_start > end:
arrows += 1
end = x_end
return arrows
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) return 0;
sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});
int arrows = 1;
int end = points[0][1];
for (int i = 1; i < points.size(); ++i) {
if (points[i][0] > end) {
++arrows;
end = points[i][1];
}
}
return arrows;
}
};
class Solution {
public int findMinArrowShots(int[][] points) {
if (points.length == 0) return 0;
Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1]));
int arrows = 1;
int end = points[0][1];
for (int i = 1; i < points.length; i++) {
if (points[i][0] > end) {
arrows++;
end = points[i][1];
}
}
return arrows;
}
}
var findMinArrowShots = function(points) {
if (!points.length) return 0;
points.sort((a, b) => a[1] - b[1]);
let arrows = 1;
let end = points[0][1];
for (let i = 1; i < points.length; i++) {
if (points[i][0] > end) {
arrows++;
end = points[i][1];
}
}
return arrows;
};
[x_start, x_end]
, meaning its diameter stretches from x_start
to x_end
on the x-axis. An arrow can be shot vertically at any x-coordinate, and it will burst all balloons whose intervals contain that x-coordinate. Each arrow can be used only once, and you must find the minimum number of arrows needed so that every balloon is burst.
x_end
). This helps us efficiently find the minimal set of non-overlapping intervals.
This greedy approach works because, by always shooting at the earliest possible end, you maximize the number of balloons burst with each arrow, ensuring optimality.
[[10,16],[2,8],[1,6],[7,12]]
[[1,6],[2,8],[7,12],[10,16]]
Result: 2 arrows are needed—one at x=6 (covering the first two balloons), and one at x=12 (covering the last two).
The greedy solution is efficient and scalable for large input sizes.