Merge Intervals - aloalgo

Merge Intervals

Medium

You are given a collection of intervals, intervals, where each intervals[i] is an array [starti, endi] representing an interval.

Your task is to merge all overlapping intervals within this collection.

Note that:

  • Each interval [starti, endi] guarantees that starti <= endi.

Return a new array containing only the non-overlapping intervals that collectively cover all intervals from the initial input.

Example 1

Input
[
  [1, 3],
  [2, 5]
]
Output
[
  [1, 5]
]
Explanation:

Intervals [1,3] and [2,5] overlap, so they are merged into [1,5].

Example 2

Input
[
  [1, 3],
  [5, 7]
]
Output
[
  [1, 3],
  [5, 7]
]
Explanation:

Intervals [1,3] and [5,7] do not overlap, so they remain separate.

Example 3

Input
[
  [1, 3],
  [3, 5],
  [7, 9]
]
Output
[
  [1, 5],
  [7, 9]
]
Explanation:

Intervals [1,3] and [3,5] overlap at the endpoint, so they are merged into [1,5]. Interval [7,9] remains separate.

Loading...
Input
[
  [1, 3],
  [2, 5]
]
Output
[
  [1, 5]
]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!