Minimum Number of Arrows to Burst Balloons

Find the fewest arrows that burst a row of overlapping balloons, by sorting them by where they end.

Balloons are stuck to a flat wall, and each one is given by the stretch it covers from left to right: a pair [xstart, xend] in the array points. An arrow shot straight up from position x bursts every balloon with xstart ≤ x ≤ xend and keeps flying. Return the fewest arrows needed to burst all the balloons. There is at least one balloon, and positions can be any int value.

Example 1
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: an arrow at 6 bursts [2,8] and [1,6]; an arrow at 12 bursts [10,16] and [7,12].
Example 2
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Example 3
Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: touching balloons can share an arrow: x = 2 and x = 4.
Solution

The Idea

Picture a wall with party balloons taped along it, some of them overlapping. You stand below with a bow, and each arrow flies straight up, so it bursts every balloon across that one spot. All that matters about a balloon is the stretch it covers, from its left edge to its right edge. A stretch given by a start and an end like this is called an interval.

Example 1 has four balloons: [10, 16], [2, 8], [1, 6] and [7, 12]. One arrow per balloon always works, but that is four arrows. [1, 6] and [2, 8] overlap from 2 to 6, so one arrow anywhere in there bursts both. [7, 12] and [10, 16] overlap from 10 to 12, so a second arrow there bursts the other two. Could one arrow do it all? No: [1, 6] ends at 6 and [10, 16] starts at 10, so no spot lies in both. The answer is 2.

With four balloons we can see the overlaps by eye. With many, the question is where to put each arrow. Start with the balloon that ends first, [1, 6]. Some arrow has to burst it, somewhere from 1 to 6. Every other balloon ends at 6 or later. So any balloon that contains the arrow's spot starts at or before that spot and ends at or after 6, which means it contains 6 as well. Moving the arrow right to 6 loses nothing, and it can only reach more balloons. Look at the picture below.

The four balloons of Example 1 sorted by end: [1, 6], [2, 8], [7, 12], [10, 16]. Arrow 1 at 6 bursts [1, 6] and [2, 8]. Arrow 2 at 12 bursts [7, 12] and [10, 16].

The balloons are listed from top to bottom in the order of their ends, under the label "sorted by end". Arrow 1 at 6 sits on the right edge of [1, 6], and it also passes through [2, 8], because [2, 8] starts at 2, which is not past 6. The next balloon, [7, 12], starts at 7, to the right of arrow 1, so arrow 1 misses it.

Now [7, 12] is the balloon that ends first among those arrow 1 missed, and the same reasoning applies to it. Arrow 2 goes at its end, 12, and passes through [10, 16] too. Every balloon is burst, with two arrows.

So the rule is: go through the balloons in order of their ends, and whenever a balloon starts past the last arrow, shoot a new arrow at that balloon's end. Taking the choice that looks best right now and never going back on it is called a greedy approach. Here the argument about the earliest end shows that the greedy choice never costs an extra arrow.

Solution Approach

Turning that rule into code means settling three things: which order to visit the balloons in, how to tell whether the last arrow bursts a balloon, and how to sort without the comparison going wrong.

Sorting by end

Why does the order go by end and not by start? Many interval problems sort by start, but here the first balloon by start can be very wide. Take [[1, 10], [2, 3], [4, 5]]. [1, 10] starts first, yet an arrow at its end, 10, misses both of the others.

Sorted by end, the same balloons read [2, 3], [4, 5], [1, 10]. The first arrow goes at 3. [4, 5] starts at 4, past 3, so a second arrow goes at 5. [1, 10] starts at 1, which is not past 5, so the second arrow bursts it. Two arrows, and two is the least possible, because [2, 3] and [4, 5] do not overlap.

Hit or miss

How do we know whether the last arrow bursts the next balloon? Keep the last arrow's position in a variable named arrowAt. Every balloon still to come ends at or after arrowAt, because of the sort. So the arrow bursts a balloon exactly when that balloon does not start past arrowAt.

The miss test is therefore "start greater than arrowAt", with a strict greater-than. A balloon that starts exactly at the arrow's position is still burst. That is what Example 3 needs: [1, 2] and [2, 3] touch at 2, so one arrow at 2 bursts both, and one at 4 bursts [3, 4] and [4, 5].

Comparing ends safely

How should the sort compare two balloons? Arrays.sort takes a comparator, a small function that gets two balloons and returns a negative number if the first should come first, and a positive number if the second should. It is often written as a subtraction of the two ends:

Java
Comparator<int[]> risky = (a, b) -> a[1] - b[1];

The trouble is that positions can be any int, from -2,147,483,648 to 2,147,483,647. The difference of two far-apart ends can be bigger than an int can store, and Java then wraps it around to a number with the wrong sign. Integer.compare(a[1], b[1]) gives the same order without subtracting, so it never wraps.

Java Solution

The method findMinArrowShots works in these steps:

  1. First, copy the array with points.clone() into sorted, so the caller's array keeps its order. Then sort sorted by end with Arrays.sort and the comparator (a, b) -> Integer.compare(a[1], b[1]).
  2. Shoot the first arrow at the end of the first balloon: arrows starts at 1 and arrowAt at sorted[0][1].
  3. Loop over each balloon b in sorted. If b[0] > arrowAt, the balloon starts past the last arrow, so add 1 to arrows and set arrowAt to b[1]. Otherwise the last arrow already bursts it. The loop meets the first balloon again, but its start is not past its own end, so it is not counted twice.
  4. After the loop, return arrows.

The main method runs the three examples, a single balloon, the case [[1, 10], [2, 3], [4, 5]] from above, and two balloons at the far ends of the int range.

Java
import java.util.Arrays;

public class MinimumArrowsToBurstBalloons {

    public static int findMinArrowShots(int[][] points) {
        int[][] sorted = points.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[1], b[1]));   // by end, no subtraction

        int arrows = 1;
        int arrowAt = sorted[0][1];          // first arrow at the end of the first balloon
        for (int[] b : sorted) {
            if (b[0] > arrowAt) {            // starts after the arrow: this balloon is missed
                arrows++;
                arrowAt = b[1];              // a new arrow at this balloon's end
            }
        }
        return arrows;
    }

    public static void main(String[] args) {
        System.out.println(findMinArrowShots(new int[][] {{10, 16}, {2, 8}, {1, 6}, {7, 12}}));
        System.out.println(findMinArrowShots(new int[][] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}));
        System.out.println(findMinArrowShots(new int[][] {{1, 2}, {2, 3}, {3, 4}, {4, 5}}));
        System.out.println(findMinArrowShots(new int[][] {{5, 9}}));
        System.out.println(findMinArrowShots(new int[][] {{1, 10}, {2, 3}, {4, 5}}));
        System.out.println(findMinArrowShots(
                new int[][] {{-2147483646, -2147483645}, {2147483646, 2147483647}}));
    }
}

Running it prints:

Output
2
4
2
1
2
2

Look at the third line, 2, from Example 3. [2, 3] starts exactly at the first arrow, at 2, and the strict test b[0] > arrowAt lets that arrow burst it. With >= in its place, every touching balloon counts as missed and that line prints 4.

The fifth line, 2, comes from [[1, 10], [2, 3], [4, 5]]. After sorting, the wide balloon [1, 10] comes last, and the arrow at 5 bursts it on the way. The last line comes from two balloons at opposite ends of the int range. They are far apart, so they need two arrows, and the code finds 2.

With the subtraction comparator from above, the last line prints 1 instead. The ends are -2,147,483,645 and 2,147,483,647, and their difference wraps around to 4, a positive number. So the sort puts [2147483646, 2147483647] first, the first arrow goes at 2,147,483,647, and the other balloon counts as burst, because its start, -2,147,483,646, is not past that arrow.

Complexity

The work is the sort, plus one pass over the sorted balloons.

  • Time: O(n log n), because sorting the n balloons by end costs O(n log n), and the pass that counts arrows does one comparison per balloon.
  • Space: O(n), because the copy sorted holds a reference to each of the n balloons, while the pass itself keeps only arrows and arrowAt.

The same idea of sorting by end and keeping what fits solves Non-overlapping Intervals.