Hide sidebar

Minimum Number of Arrows to Burst Balloons

Minimum Number of Arrows to Burst Balloons

GreedyIntervals
MediumLeetCode #452
20 min

Problem Statement

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrows can be shot up vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example

Example 1:

Input: points = [[10,16],[2,8],[1,6],[7,12]]

points: [[10,16],[2,8],[1,6],[7,12]]

Output: 2

Output: 2

Solution

The greedy approach is to sort the balloons by their end points. We shoot an arrow at the end of the first balloon. This arrow will burst all balloons that overlap with this point. Then we move to the next unburst balloon and repeat the process.

Algorithm Steps

  • Sort the `points` array based on the end points.
  • Initialize `arrows` to 1 and `end` to the end point of the first balloon.
  • Iterate through the rest of the balloons.
  • If the current balloon's start point is greater than `end`, it means we need a new arrow. Increment `arrows` and update `end` to the current balloon's end point.
  • Return `arrows`.

Minimum Number of Arrows to Burst Balloons

Greedy Approach

Input: points = [[10,16],[2,8],[1,6],[7,12]]

Output: 0

Progress1 / 1

Ready to start the visualization

Points

[10, 16]
[2, 8]
[1, 6]
[7, 12]

Arrows

0

Current Arrow End

0
Minimum Number of Arrows to Burst Balloons Solution

class Solution:
    def findMinArrowShots(self, points: list[list[int]]) -> int:
        if not points:
            return 0
        
        points.sort(key = lambda i : i[1])
        arrows = 1
        end = points[0][1]
        
        for i in range(1, len(points)):
            if points[i][0] > end:
                arrows += 1
                end = points[i][1]
        return arrows