Problem · Intervals

Merge Intervals

Learn this problem
MediumMicrosoft logoMicrosoftNEW GRADONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

Given an array of closed intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals.

Intervals that share an endpoint overlap. Return the non-overlapping intervals that cover every input interval, sorted by increasing start value.

Function

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

Examples

Example 1

intervals = [[1,3],[2,6],[8,10],[15,18]]return = [[1,6],[8,10],[15,18]]

Intervals [1,3] and [2,6] overlap and merge into [1,6]. The other intervals remain separate.

Example 2

intervals = [[1,4],[4,5]]return = [[1,5]]

The intervals share endpoint 4, so the closed intervals overlap.

Example 3

intervals = [[8,10],[1,4],[2,3],[15,18],[6,9],[3,7],[17,20],[12,12]]return = [[1,10],[12,12],[15,20]]

Sorting exposes two overlap chains: the intervals from [1,4] through [8,10] merge into [1,10], and the last two merge into [15,20].

Constraints

  • 1 <= intervals.length <= 10000
  • intervals[i].length == 2
  • -10^9 <= start_i <= end_i <= 10^9

More Microsoft problems

drafts saved locally
public int[][] merge(int[][] intervals) {
  // write your code here
}
intervals[[1,3],[2,6],[8,10],[15,18]]
expected[[1,6],[8,10],[15,18]]
checking account