Minimum Arrow Shots

Moderate
0/80
0 upvote
Asked in company
HCL Technologies

Problem statement

You are given a 2D integer array points where points[i] = [xstart, xend] represents the horizontal diameter of a spherical balloon. You are shooting arrows vertically upwards from the x-axis.

An arrow shot at position x on the x-axis will burst any balloon whose xstart <= x <= xend. A single arrow can burst multiple balloons if their horizontal diameters overlap with the arrow's path.

Your task is to find the minimum number of arrows that must be shot to burst all the balloons.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'N', the number of balloons.

The next 'N' lines each contain two space-separated integers, x_start and x_end.


Output Format:
Print a single integer representing the minimum number of arrows required.


Note:
A key insight to solve this problem greedily is to sort the balloons. Sorting by the end coordinate (x_end) is a highly effective strategy.
Sample Input 1:
4
10 16
2 8
1 6
7 12


Sample Output 1:
2


Explanation for Sample 1:
Sort the balloons by their end points: `[1,6], [2,8], [7,12], [10,16]`.
1.  Shoot the first arrow at x=6 to burst the `[1,6]` balloon. This arrow's position is now 6.
2.  Consider the `[2,8]` balloon. Its start (2) is less than or equal to the arrow's position (6). So, this balloon is also burst by the same arrow.
3.  Consider the `[7,12]` balloon. Its start (7) is greater than the arrow's position (6). We need a new arrow. Increment arrow count to 2. Shoot this new arrow at x=12. The new arrow's position is 12.
4.  Consider the `[10,16]` balloon. Its start (10) is less than or equal to the new arrow's position (12). This balloon is also burst.
All balloons are burst with 2 arrows.


Sample Input 2:
4
1 2
3 4
5 6
7 8


Sample Output 2:
4


Explanation for Sample 2:
The balloons `[1,2], [3,4], [5,6], [7,8]` have no overlapping horizontal diameters. Therefore, each balloon requires its own arrow.


Expected Time Complexity:
The expected time complexity is O(N log N).


Constraints:
1 <= N <= 10^5
-2^31 <= x_start < x_end <= 2^31 - 1

Time limit: 1 sec
Approaches (1)
Minimum Arrow Shots
Time Complexity

The expected time complexity is O(N log N)

Space Complexity
Code Solution
(100% EXP penalty)
Minimum Arrow Shots
Full screen
Console