Minimum Number of Arrows to Burst Balloons
Minimum Number of Arrows to Burst Balloons
Problem Statement
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points
where points[i] = [xstart, xend]
denotes a balloon whose horizontal diameter stretches between xstart
and xend
. You do not know the exact y-coordinates of the balloons. Arrows can be shot up vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points
, return the minimum number of arrows that must be shot to burst all balloons.
Example
Input: points = [[10,16],[2,8],[1,6],[7,12]]
points: [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Output: 2
Solution
The greedy approach is to sort the balloons by their end points. We shoot an arrow at the end of the first balloon. This arrow will burst all balloons that overlap with this point. Then we move to the next unburst balloon and repeat the process.
Algorithm Steps
- Sort the `points` array based on the end points.
- Initialize `arrows` to 1 and `end` to the end point of the first balloon.
- Iterate through the rest of the balloons.
- If the current balloon's start point is greater than `end`, it means we need a new arrow. Increment `arrows` and update `end` to the current balloon's end point.
- Return `arrows`.
Minimum Number of Arrows to Burst Balloons
Greedy Approach
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 0
Ready to start the visualization
Points
Arrows
Current Arrow End