Problem 452 · LeetCode 452(opens in a new tab)
Minimum Number of Arrows to Burst Balloons
MediumGreedy algorithms
Balloons are stretched along a line. Balloon i covers every position from points[i][0] to points[i][1], both ends included.
An arrow fired at position x pops every balloon whose range contains x, and it keeps going, so one arrow can pop many balloons. Return the fewest arrows that pop them all.
Example 1
Input: points = [[3, 9], [11, 15], [1, 4], [7, 12], [2, 5]] Output: 2 Why: x = 4 pops three balloons, x = 12 the other two
2 more examples and the constraints
Example 2
Input: points = [[1, 3], [5, 6], [8, 10]] Output: 3 Why: no two balloons overlap
Example 3
Input: points = [[1, 3], [3, 6], [6, 9], [9, 12]] Output: 2 Why: touching ends count: x = 3 and x = 9
Constraints
- 1 ≤ number of balloons ≤ 100,000
- Each balloon is a pair [start, end] with start < end
- −2^31 ≤ start, end ≤ 2^31 − 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort by start, shrink the overlapO(n log n)
- Sort by end, shoot at the endO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 balloons | Verdict |
|---|---|---|---|
| Sort by start, shrink the overlap | O(n log n) | Passes; one more min per step | |
| Sort by end, shoot at the end | O(n log n) | Best; the classic greedy |
n = how many balloons there are. Both are dominated by the sort.
Edge cases to test
- One balloon. Always one arrow.
- Touching ends. [1, 3] and [3, 6] share the point 3, so one arrow pops both. Use
>, not>=, when testing for a miss. - One balloon inside another. [[1, 10], [2, 3], [4, 5]] needs 2. Sorting by start and keeping only the first end would wrongly say 1.
- Extreme coordinates. Ends at −2^31 and 2^31 − 1 overflow a subtracting comparator.
Common mistakes
- Sorting by start and shooting at the first balloon's end without shrinking it, so a short balloon nested inside a long one is missed.
- Writing the comparator as
a[1] - b[1]in Java or C++, which overflows on the extreme values. - Testing
start >= arrowfor a miss, which counts touching balloons as separate.
How to talk through it
- 1Clarify. Are the ends inclusive? Can balloons share an endpoint? How large can the coordinates be?
- 2Reframe. This is choosing the fewest points so that every interval holds one.
- 3Argue the greedy. The balloon that ends first needs an arrow; putting it at that end hits as many others as any spot could.
- 4Code the sweep. Sort by end, keep the last arrow, add an arrow when a balloon starts after it.
- 5Test out loud. Run touching ends, a nested balloon and the extreme coordinates.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?