Blind 75
64 / 75Free practice

Merge Intervals

Medium · Intervals

Jump to code

Merge all overlapping closed intervals from an unsorted list and return a list sorted by start. Intervals touching at an endpoint should merge.

Examples

Example 1

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

Output: [[1,6],[8,10],[15,18]]

Example 2

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

Output: [[1,5]]

Constraints

  • 1 <= intervals.length <= 1000
  • intervals[i].length == 2
  • 0 <= start <= end <= 1000
Need a hint?

Sorting makes every possible overlap adjacent to the current merged interval.

Asked in real interviews

Candidates reported versions of Merge Intervals from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      3
    ],
    [
      2,
      6
    ],
    [
      8,
      10
    ],
    [
      15,
      18
    ]
  ]
]
Expected
[
  [
    1,
    6
  ],
  [
    8,
    10
  ],
  [
    15,
    18
  ]
]
Case 2
Input
[
  [
    [
      1,
      4
    ],
    [
      4,
      5
    ]
  ]
]
Expected
[
  [
    1,
    5
  ]
]
Case 3
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ]
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    4
  ]
]
Case 4
Input
[
  [
    [
      1,
      10
    ],
    [
      2,
      3
    ],
    [
      4,
      5
    ]
  ]
]
Expected
[
  [
    1,
    10
  ]
]
Case 5
Input
[
  [
    [
      5,
      6
    ],
    [
      1,
      4
    ]
  ]
]
Expected
[
  [
    1,
    4
  ],
  [
    5,
    6
  ]
]

Drafts are saved per language in this browser when storage is available.