Date and Time: Sep 6, 2024, 15:44 (EST)
Link: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
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] = [x_start, x_end]
denotes a balloon whose horizontal diameter stretches between x_start
and x_end
. 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 x_start
and x_end
is burst by an arrow shot at x
if x_start <= x <= x_end
. 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 1:
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
Example 2:
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
Example 3:
Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].
-
1 <= points.length <= 10^5
-
points[i].length == 2
-
-2^31 <= x_start < x_end <= 2^31 - 1
-
We sort
points
first so we can more easily to find the overlapping intervals. -
We set
res = len(points)
and useprev
to keep track of the previous overlapped interval (the range where two intervals overlapped), then we decrementres
if we find an overlap between two intervals. We know overlap if the current intervalpoints[i][0] < prev[1]
, then we updateprev = [points[i][0], min(points[i][1], prev[1])]
(the range where two intervals overlapped). Otherwise, we updateprev = points[i]
.
Of course, we can use prev
to store the last element of points[i]
, and each time we only check if points[i][1] <= prev
, make corresponding update to prev
.
Example 1:
[1, 6]
[2, 8] -> prev = [2, 6]
[7, 12]
[10, 16]
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# Sort points, count len(points)
# Use prev to compare with points[i], if start <= prev[1]: decrement res, and update prev
# Otherwise, start > prev[1]: directly update prev to be current points[i]
# TC: O(nlogn), n=len(points), SC: O(1)
points.sort()
prev = points[0]
res = len(points)
for start, end in points[1:]:
if start <= prev[1]:
res -= 1
prev = [start, min(end, prev[1])]
else:
prev = [start, end]
return res
Time Complexity: points
and loop over points
.
Space Complexity: