FastPrepMerge Intervals

Merge Intervals

Fractal Analytics logoFractal Analytics● MediumFULLTIMEPHONE SCREEN

Problem statement

You are given an array intervals where intervals[i] = [start_i, end_i] is the closed interval of all numbers from start_i to end_i, endpoints included. The intervals can come in any order.

Merge every group of intervals that share at least one point, and return the merged intervals sorted by their start. Two intervals that only touch, such as [2, 5] and [5, 7], share the point 5 and must be merged.

Function

mergeIntervals(intervals: int[][]) → int[][]

Examples

Example 1

intervals = [[8,12],[1,4],[3,6],[10,11]]return = [[1,6],[8,12]]

[1, 4] and [3, 6] overlap on 3 to 4, so they merge into [1, 6]. [10, 11] lies inside [8, 12], so together they stay [8, 12]. The result is listed by start.

Example 2

intervals = [[5,7],[2,5]]return = [[2,7]]

The two intervals touch at 5. Touching intervals share a point, so they merge into [2, 7].

Example 3

intervals = [[9,9],[0,2],[4,6]]return = [[0,2],[4,6],[9,9]]

No two intervals share a point, so nothing merges. [9, 9] is a single point. The intervals are returned in order of their starts.

Constraints

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= start_i <= end_i <= 10^9
See Fractal Analytics hiring insights
Saved
public int[][] mergeIntervals(int[][] intervals) {
    // Write your code here.
}
Checking account…