Coding Practice: Minimum Number of Arrows to Burst Balloons

0 min read Tweet this post

https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/

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].
type Points [][]int

func (point Points) Len() int {
	return len(point)
}

func (point Points) Swap(i, j int) {
	point[i], point[j] = point[j], point[i]
}

func (point Points) Less(i, j int) bool {
	return point[i][1] < point[j][1]
}


func findMinArrowShots(points [][]int) int {
	intervals := Points(points)
	if len(intervals) == 0 {
		return 0
	}

	sort.Sort(intervals)

	count := 1
	start := intervals[0][1]
	for i := 1; i < len(intervals); i++ {
		// When we encounter a new balloon, if its start `x-coordinate` is less than or equal to the rightmost end point, we don't need to shoot a new arrow as the current arrow will burst the new balloon as well.
		if intervals[i][0] <= start {
			continue
		}
		count++
		start = intervals[i][1]
	}

	return count
}
programming go practice leetcode