Merge Overlapping Intervals
Problem statement
You are given a list of closed intervals [start, end] in any order. Two intervals overlap if they share at least one point; intervals that only touch at an end, like [1, 5] and [5, 6], also count.
Merge every group of overlapping intervals (including chains, where A overlaps B and B overlaps C) into one interval that covers the group. Return the merged intervals sorted by start.
Function
mergeIntervals(intervals: int[][]) → int[][]Examples
Example 1
intervals = [[9,12],[2,5],[4,7],[14,14]]return = [[2,7],[9,12],[14,14]][2, 5] and [4, 7] overlap on 4 to 5, so they become [2, 7]. [9, 12] and [14, 14] touch nothing else. Sorted by start: [2, 7], [9, 12], [14, 14].
Example 2
intervals = [[5,6],[1,5],[6,10]]return = [[1,10]][1, 5] and [5, 6] share the point 5, and [5, 6] and [6, 10] share 6, so all three join into [1, 10]. Intervals that only touch at an end point count as overlapping.
Example 3
intervals = [[3,20],[4,8],[10,11]]return = [[3,20]][4, 8] and [10, 11] lie inside [3, 20], so the answer is just [3, 20].
Constraints
1 <= intervals.length <= 2000- each
intervals[i] = [start, end]with0 <= start <= end <= 10^9