Find Minimum Number Of Arrows Needed To Burst All Balloons

Given an array points[][] of size N, where points[i] represents a balloon over the area of X-coordinates from points[i][0] to points[i][1]. The Y-coordinates don’t matter. All the balloons are required to be burst. To burst a balloon, an arrow can be launched at point (x, 0) and it travels vertically upwards and bursts all the balloons which satisfy the condition points[i][0] <= x <= points[i][1]. The task is to find the minimum number of arrows required to burst all the balloons.
Examples:
Input: N = 4, points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}
Output: 2
Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2, 8] and [1, 6]) and another arrow at x = 11 (bursting the other two balloons).Input: N = 1, points = {{1, 6}}
Output: 1
Explanation: One single arrow can burst the balloon.
Approach: The given problem can be solved by using the Greedy Approach to find the balloons which are overlapping with each other so that the arrow can pass through all such balloons and burst them. To do that optimally, sort the array with respect to the X-coordinate in ascending order. So, now consider 2 balloons, if the second balloon is starting before the first balloon then it must be ending after the first balloon or at the same position.
For example [1, 6], [2, 8] -> the second balloon starting position i.e 2 which is before the ending position of the first balloon i.e 6, and since the array is sorted the end of the second balloon is always greater than the end of the first balloon. The second balloon end i.e 8 is after the end of the first balloon i.e 6. which shows us the overlapping is there between [2, 6].
Follow the steps below to solve the problem:
- Sort the array according to the end position of balloons using the comparator/lambda expression Arrays.sort(points, (a, b)-> Integer.compare(a[1], b[1])).
- Make a variable arrow and initialize it with 1( as a minimum one arrow is going to be needed to burst the balloons )
- Make a variable end and initialize it with points[0][1] that will be storing the end of the first balloon.
- Iterate over the range [1, N) using the variable i and perform the following steps:
- Check whether the start of the next balloon points[i][0] is less than the end variable end.
- If so, then continue the iteration.
- Else, increase the count of the arrow by 1 and set the value of end as points[i][1].
- After completing the above steps, print the value of arrow as the resultant count of arrows required.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
bool cmp(vector<int> a, vector<int> b){Â Â Â Â return b[1] > a[1];}Â
// Function to find the minimum count of// arrows required to burst all balloonsint minArrows(vector<vector<int>> points){       // To sort our array according    // to end position of balloons    sort(points.begin(), points.end(), cmp);Â
    // Initialize end variable with    // the end of first balloon    int end = points[0][1];Â
    // Initialize arrow with 1    int arrow = 1;Â
    // Iterate through the entire    // arrow of points    for (int i = 1; i < points.size(); i++)    {Â
        // If the start of ith balloon        // <= end than do nothing        if (points[i][0] <= end)        {            continue;        }Â
        // if start of the next balloon        // >= end of the first balloon        // then increment the arrow        else        {Â
            // Update the new end            end = points[i][1];            arrow++;        }    }Â
    // Return the total count of arrows    return arrow;}Â
// Driver codeint main(){Â
    vector<vector<int>> points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}};    cout << (minArrows(points));    return 0;}Â
// This code is contributed by Potta Lokesh |
Java
// Java program for the above approachimport java.io.*;import java.util.*;Â
class GFG {Â
    // Function to find the minimum count of    // arrows required to burst all balloons    public static int minArrows(int points[][])    {        // To sort our array according        // to end position of balloons        Arrays.sort(points,                    (a, b) -> Integer.compare(a[1], b[1]));Â
        // Initialize end variable with        // the end of first balloon        int end = points[0][1];Â
        // Initialize arrow with 1        int arrow = 1;Â
        // Iterate through the entire        // arrow of points        for (int i = 1; i < points.length; i++) {Â
            // If the start of ith balloon            // <= end than do nothing            if (points[i][0] <= end) {                continue;            }Â
            // if start of the next balloon            // >= end of the first balloon            // then increment the arrow            else {Â
                // Update the new end                end = points[i][1];                arrow++;            }        }Â
        // Return the total count of arrows        return arrow;    }Â
    // Driver Code    public static void main(String[] args)    {        int[][] points            = { { 10, 16 }, { 2, 8 }, { 1, 6 }, { 7, 12 } };Â
        System.out.println(            minArrows(points));    }} |
Python3
# Python3 program for the above approachÂ
# Function to find the minimum count of# arrows required to burst all balloonsdef minArrows(points):Â
    # To sort our array according    # to end position of balloons    points = sorted(points, key = lambda x:x[1])Â
    # Initialize end variable with    # the end of first balloon    end = points[0][1];Â
    # Initialize arrow with 1    arrow = 1;Â
    # Iterate through the entire    # arrow of points    for i in range (1, len(points)) :Â
        # If the start of ith balloon          # <= end than do nothing        if (points[i][0] <= end) :            continue;     Â
        # if start of the next balloon        # >= end of the first balloon        # then increment the arrow        else :Â
            # Update the new end            end = points[i][1]                   arrow = arrow + 1        # Return the total count of arrows    return arrow;Â
# Driver Codepoints = [[10, 16 ], [ 2, 8 ], [1, 6 ], [ 7, 12 ]] print(minArrows(points))Â Â Â # This code is contributed by AR_Gaurav |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG {Â
    // Function to find the minimum count of    // arrows required to burst all balloons    public static int minArrows(int[][] points)    {        // To sort our array according        // to end position of balloons        // Array.Sort(points, (a, b) => {return a[1] - b[1];});        Comparer<int> comparer = Comparer<int>.Default;        Array.Sort<int[]>(points, (x,y) => comparer.Compare(x[1],y[1]));         Â
        // Initialize end variable with        // the end of first balloon        int end = points[0][1];Â
        // Initialize arrow with 1        int arrow = 1;Â
        // Iterate through the entire        // arrow of points        for (int i = 1; i < points.Length; i++) {Â
            // If the start of ith balloon            // <= end than do nothing            if (points[i][0] <= end) {                continue;            }Â
            // if start of the next balloon            // >= end of the first balloon            // then increment the arrow            else {Â
                // Update the new end                end = points[i][1];                arrow++;            }        }Â
        // Return the total count of arrows        return arrow;    }Â
    // Driver Code    public static void Main(String[] args)    {        int[][] points            = { new int[] { 10, 16 }, new int[] { 2, 8 }, new int[]{ 1, 6 }, new int[]{ 7, 12 } };Â
        Console.Write(minArrows(points));    }}Â
// This code is contributed by saurabh_jaiswal. |
Javascript
<script>// Javascript program for the above approachÂ
function cmp(a, b) {Â Â return a[1] - b[1];}Â
// Function to find the minimum count of// arrows required to burst all balloonsfunction minArrows(points){Â
  // To sort our array according  // to end position of balloons  points.sort(cmp);Â
Â
  // Initialize end variable with  // the end of first balloon  let end = points[0][1];Â
  // Initialize arrow with 1  let arrow = 1;Â
  // Iterate through the entire  // arrow of points  for (let i = 1; i < points.length; i++) {    // If the start of ith balloon    // <= end than do nothing    if (points[i][0] <= end) {      continue;    }Â
    // if start of the next balloon    // >= end of the first balloon    // then increment the arrow    else {      // Update the new end      end = points[i][1];      arrow++;    }  }Â
  // Return the total count of arrows  return arrow;}Â
// Driver codelet points = [  [10, 16],  [2, 8],  [1, 6],  [7, 12],];document.write(minArrows(points));Â
// This code is contributed by gfgking.</script> |
2
Â
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
The Different  Code Do It :
C++
#include<bits/stdc++.h>using namespace std;Â
  // an arrow shot at x if xstart ≤ x ≤ xendint findMinArrowShots(vector<vector<int>>& points) {       // Arrays.sort(points, Comparator.comparingInt(p -> p[1]));    sort(points.begin(), points.end());    long max = 0, last = LONG_MIN;    for (auto p : points) {        if (last < p[0]) {             last = p[1];            max++;        }    }    return max;}Â
int main() {Â Â Â Â vector<vector<int>>points={{10, 16}, {2, 8}, {1, 6}, {7, 12}};Â Â Â Â cout << findMinArrowShots(points);}Â
 // This code is contributed by ritaagarwal. |
Java
/*package whatever //do not write package name here */Â
import java.io.*;import java.lang.*;import java.util.*;class GFG {  // an arrow shot at x if xstart ≤ x ≤ xend    public static int findMinArrowShots(int[][] points) {        Arrays.sort(points, Comparator.comparingInt(p -> p[1]));        long max = 0, last = Long.MIN_VALUE;        for (int[] p : points) {            if (last < p[0]) {                 last = p[1];                max++;            }        }        return (int) max;    }    public static void main(String[] args) {        int [][]points={{10, 16}, {2, 8}, {1, 6}, {7, 12}};        System.out.println(findMinArrowShots(points));    }} |
Javascript
// an arrow shot at x if xstart ≤ x ≤ xendfunction findMinArrowShots(points) {       // Arrays.sort(points, Comparator.comparingInt(p -> p[1]));    points.sort();         //sort(points.begin(), points.end());    let max = 0, last = -9223372036854775808;    for (let p of points) {        if (last < p[0]) {             last = p[1];            max++;        }    }    return max;}Â
let points=[[10, 16], [2, 8], [1, 6], [7, 12]];console.log(findMinArrowShots(points));Â
// This code is contributed by poojaagarwal2. |
C#
// C# code to implement the approachÂ
using System;using System.Collections.Generic;Â
class GFG {      // an arrow shot at x if xstart ≤ x ≤ xend    static long findMinArrowShots(List<List<int>> points)     {               // Arrays.sort(points, Comparator.comparingInt(p -> p[1]));        points.Sort((x, y) => x[0].CompareTo(y[0]));Â
        long max = 0, last = -2147483648;        for (int i=0; i<points.Count; i++) {            List<int>p=points[i];            if (last < p[0]) {                 last = p[1];                max++;            }        }        return max;    }         public static void Main()    {        List<List<int>>points=new List<List<int>>();        points.Add(new List<int>{10, 16});         points.Add(new List<int>{2, 8});        points.Add(new List<int>{1, 6});        points.Add(new List<int>{7, 12});        Console.Write(findMinArrowShots(points));    }Â
} |
Python3
def findMinArrowShots(points):Â Â Â Â # Arrays.sort(points, Comparator.comparingInt(p -> p[1]));Â Â Â Â points.sort()Â Â Â Â maxVal = 0Â Â Â Â lastVal = float('-inf')Â Â Â Â for p in points:Â Â Â Â Â Â Â Â if lastVal < p[0]:Â Â Â Â Â Â Â Â Â Â Â Â lastVal = p[1]Â Â Â Â Â Â Â Â Â Â Â Â maxVal += 1Â Â Â Â return maxValÂ
Â
points = [[10, 16], [2, 8], [1, 6], [7, 12]]print(findMinArrowShots(points)) |
2
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



