Find Minimum Number Of Arrows Needed To Burst All Balloons

30 Nov, 2021
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: 2Explanation: 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: 1Explanation: 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].
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++
Java
Python3
C#
Javascript
// 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 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 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# 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.
<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)
lokeshpotta20
AR_Gaurav
gfgking
_saurabh_jaiswal
Arrays
Greedy
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3