452. Minimum Number of Arrows to Burst Balloons ๐
Difficulty: Medium
- Tags: Greedy
, Intervals
, Sorting
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
.
Arrows can be shot up vertically along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
.
Task: Return the minimum number of arrows required to burst all balloons.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation:
Shoot an arrow at
x = 6
, bursting the balloons[2,8]
and[1,6]
.Shoot another arrow at
x = 11
, bursting the balloons[10,16]
and[7,12]
.
๐น Example 2:
Input:
Output:
Explanation: Each balloon requires a separate arrow.
๐น Example 3:
Input:
Output:
Explanation:
Shoot an arrow at
x = 2
, bursting the balloons[1,2]
and[2,3]
.Shoot another arrow at
x = 4
, bursting the balloons[3,4]
and[4,5]
.
Constraints โ๏ธ
1 <= points.length <= 10^5
points[i].length == 2
-2^31 <= xstart < xend <= 2^31 - 1
Solution ๐ก
To solve the problem, follow these steps:
Sort the
points
array by the ending position of each interval.Use a greedy approach to minimize the number of arrows:
Start with one arrow to burst the first interval.
For each subsequent interval, check if it overlaps with the previous interval:
If it does, continue with the current arrow.
Otherwise, shoot a new arrow.
Java Solution
Explanation of the Solution
Sorting by End Points:
Sorting ensures that we process balloons in order of their earliest end point.
This allows us to maximize the coverage of a single arrow.
Tracking Overlaps:
Start with one arrow at the end of the first balloon.
If the next balloon starts after the current arrow's range (
points[i][0] > currentEnd
), shoot a new arrow.Otherwise, the current arrow is sufficient to burst overlapping balloons.
Time Complexity โณ
O(n log n): Sorting the balloons array dominates the time complexity.
O(n): Linear traversal of the sorted intervals.
Space Complexity ๐พ
O(1): Sorting is in-place, and no additional space is used.
You can find the full solution here.
Last updated