Insert Interval - aloalgo

Insert Interval

Medium

You are given a list of non-overlapping intervals, intervals, where each intervals[i] is represented as [start_i, end_i], and a newInterval in [start, end] format.

Your task is to insert newInterval into the intervals list, ensuring the resulting list remains sorted by start times and contains no overlapping intervals, merging any overlaps that occur.

You may assume that:

  • Each interval [start, end] represents an inclusive range.
  • The initial intervals list is non-overlapping.
  • The initial intervals list is sorted by start times.

Return the merged list of intervals.

Example 1

Inputs
intervals = [
  [1, 3],
  [6, 7]
]
newInterval = [2, 3]
Output
[
  [1, 3],
  [6, 7]
]
Explanation:

The new interval [2,3] overlaps with [1,2]. Merging these results in [1,3].

Example 2

Inputs
intervals = [
  [1, 3],
  [6, 9]
]
newInterval = [4, 5]
Output
[
  [1, 3],
  [4, 5],
  [6, 9]
]
Explanation:

The new interval [4,5] does not overlap with any existing intervals. It is simply inserted in the correct position.

Example 3

Inputs
intervals = [
  [1, 2],
  [6, 9]
]
newInterval = [2, 7]
Output
[
  [1, 9]
]
Explanation:

The new interval [2,7] overlaps with both [1,2] and [6,9]. Merging these results in [1,9].

Loading...
Inputs
intervals = [
  [1, 3],
  [6, 7]
]
newInterval = [2, 3]
Output
[
  [1, 3],
  [6, 7]
]

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!