Back

Merge Intervals

medium

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Test Cases

Copy an input into the main harness and Run to verify
Input
intervals = [[1,3],[2,6],[8,10],[15,18]]
Expected Output
[[1,6],[8,10],[15,18]]

Explanation: Intervals [1,3] and [2,6] overlap and are merged into [1,6].

Input
intervals = [[1,4],[4,5]]
Expected Output
[[1,5]]

Constraints

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= start_i <= end_i <= 10^4

Hints

Hint 1 — click to reveal

Sort by start time first.

Hint 2 — click to reveal

If the current interval starts after the last merged one ends, they don't overlap.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.