Minimum Number of Arrows to Burst Balloons
MediumTop Interview 150 IntervalsProblem
Each element of points is a balloon described by the span [start, end] it covers on a
horizontal line. An arrow shot straight up from position x bursts every balloon whose span contains
x, including balloons where x is exactly an end.
Arrows keep flying after bursting balloons. Return the smallest number of arrows that bursts all the balloons.
Constraints
- 1 ≤ points.length ≤ 10⁵
- points[i].length == 2
- −2³¹ ≤ start < end ≤ 2³¹ − 1
Examples: pick one to animate
Solutions
Time: Sorting costs O(n log n); the pass over the balloons is O(n).
Space: Only the arrow count and the last arrow position are kept (not counting the sort's own working space).
Sort the balloons by right edge. Shoot the first arrow at the first balloon's right edge: that is as far right as it can go while still popping it, so it reaches the most balloons. For each next balloon, if it starts at or before the last arrow, that arrow already pops it. Otherwise it needs a new arrow, placed at its own right edge.