Practice › Greedy
Minimum Arrows to Burst Balloons
Medium · Greedy · Asked at Amazon, Microsoft, Meta, Flipkart
Each balloon covers the horizontal interval [s, e]. An arrow shot straight up at position x bursts every balloon with s ≤ x ≤ e. Print the minimum number of arrows needed to burst all balloons.
Input
First line: n. Next n lines: s e.
Output
The minimum number of arrows.
Constraints
- 1 ≤ n ≤ 10^5
- −2^31 ≤ s ≤ e ≤ 2^31 − 1
Sort balloons by their end. Shoot an arrow at the end of the first balloon; it bursts every balloon starting at or before that point. The next balloon not burst needs a new arrow at its end.
Example 1
Input
4 10 16 2 8 1 6 7 12
Output
2
Example 2
Input
4 1 2 3 4 5 6 7 8
Output
4
Hints
- Look at the balloon that ends first. Some arrow must hit it, at or before its end.
- Shooting exactly at its end bursts it and as many others as possible.
- Sort by end and sweep.
Approach
Sort the balloons by their end. Keep the position of the last arrow. For each balloon in order: if it starts after the last arrow, that arrow missed it — shoot a new arrow at this balloon's end. Otherwise it is already burst. Coordinates reach ±2^31, so use 64-bit integers (and avoid "end1 − end2" in comparators, which can overflow).
Complexity: O(n log n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pair<long long, long long>> b(n); // (end, start)
for (auto &p : b) cin >> p.second >> p.first;
sort(b.begin(), b.end());
int arrows = 0;
long long at = LLONG_MIN;
for (auto &x : b)
if (arrows == 0 || x.second > at) {
arrows++;
at = x.first;
}
cout << arrows << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
balloons = sorted(((data[2 + 2 * i], data[1 + 2 * i]) for i in range(n)))
arrows = 0
at = None
for end, start in balloons:
if at is None or start > at:
arrows += 1
at = end
print(arrows)Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[][] b = new long[n][2];
for (int i = 0; i < n; i++) {
in.nextToken();
b[i][0] = (long) in.nval;
in.nextToken();
b[i][1] = (long) in.nval;
}
Arrays.sort(b, (x, y) -> Long.compare(x[1], y[1]));
int arrows = 0;
long at = Long.MIN_VALUE;
for (long[] x : b)
if (arrows == 0 || x[0] > at) {
arrows++;
at = x[1];
}
System.out.println(arrows);
}
}Solve Minimum Arrows to Burst Balloons online · All practice problems