AAlgoLoopSpaced repetition for LeetCode
MEDIUMGreedyLeetCode ↗

Minimum Number of Arrows to Burst Balloons

The key idea

Sort the balloons by their end coordinate. Shoot an arrow at the end of the first balloon; it bursts every later balloon whose start is at or before that arrow. Only when a balloon starts past the current arrow do you need a new arrow, placed at that balloon's end.

Problem

There are some spherical balloons taped to a flat wall that represents the XY-plane. The balloons are given 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 directly 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.

Constraints

Examples

Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2
Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4
Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2

Complexity

Time: O(n log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Greedy problems