Polski

Merge intervals

Join overlapping and touching time intervals into disjoint blocks. Sorting plus a single pass – and a few traps with intervals nested inside others.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A team calendar has to show the hours when anyone is busy. Every meeting is an interval [start, end] (minutes after midnight); meetings may overlap and arrive in any order. Merge them into as few disjoint blocks as possible.

Task

Return a new list of intervals:

  • intervals that overlap or touch ([1, 3] and [3, 5]) are merged into one,
  • the result is sorted by start, and its intervals are disjoint and do not touch,
  • the input must not be modified (neither the order nor the values).

Signatures: mergeIntervals(intervals) (JS/TS), merge_intervals(intervals) (Python), Solution.MergeIntervals (C#, int[][]), Solution.mergeIntervals (Java, int[][]), MergeIntervals (Go, [][]int).

Examples

InputResult
[[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]
[[1,4],[4,5]][[1,5]] – touching
[[8,10],[1,3],[2,6]][[1,6],[8,10]] – unsorted
[[1,10],[2,3],[4,5]][[1,10]] – nested in the first one
[][]

Constraints

  • 0 ≤ n ≤ 100,000, -10⁹ ≤ start ≤ end ≤ 10⁹.

Expected complexity

O(n log n) time (sorting), O(n) extra memory for the copy and the result.