Merge Intervals from Start and End Lists
Problem statement
You are given two integer arrays starts and ends of the same length. Together they describe time intervals: interval i runs from starts[i] to ends[i], both ends included. The intervals are in no particular order.
Merge every group of overlapping intervals into one interval. Two intervals overlap when each one starts at or before the moment the other ends, so intervals that only touch, such as [1, 4] and [4, 6], are merged into [1, 6].
Return the merged intervals as pairs [start, end], sorted by start time. No two returned intervals overlap or touch.
Function
mergeIntervals(starts: int[], ends: int[]) → int[][]Examples
Example 1
starts = [5,1,10,2]ends = [8,4,12,5]return = [[1,8],[10,12]]The intervals are [5,8], [1,4], [10,12] and [2,5]. Sorted by start: [1,4] and [2,5] overlap into [1,5], which touches [5,8] at 5, giving [1,8]. [10,12] starts after 8, so it stays separate.
Example 2
starts = [7,0,7]ends = [7,2,7]return = [[0,2],[7,7]]Two copies of the single moment [7,7] merge into one. [0,2] ends before 7.
Example 3
starts = [3,4,20]ends = [30,6,21]return = [[3,30]][4,6] and [20,21] lie inside [3,30], so the merged interval keeps the end 30.
Constraints
1 <= starts.length <= 2000ends.length == starts.length0 <= starts[i] <= ends[i] <= 10^9