KatInterview

Insert and Merge Interval into Sorted Collection

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalsintervalsarraysgreedy

Last updated

Incorporate a target range into an already sorted list of disjoint closed intervals, merging any overlapping or adjacent spans in linear time.

Given a list of disjoint, closed integer intervals intervals sorted in ascending order by their start points, and a single interval new_interval, insert new_interval into the collection.

If adding new_interval causes any ranges to overlap or touch, combine them into a single merged interval. Return the resulting list of intervals, which must remain sorted by start point and contain no overlapping ranges.

Two closed intervals $[a, b]$ and $[c, d]$ are considered touching (and thus must be merged) if they share a boundary, i.e., when $c \le b$ and $a \le d$.

Constraints

  • 0 <= len(intervals) <= 10^4
  • len(intervals[i]) == 2
  • len(new_interval) == 2
  • -10^9 <= intervals[i][0] <= intervals[i][1] <= 10^9
  • -10^9 <= new_interval[0] <= new_interval[1] <= 10^9
  • intervals is sorted by start point in non-decreasing order.
  • intervals contains no overlapping ranges prior to insertion.

Examples

Example 1

Input: insert_interval([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8])

Output: [[1, 2], [3, 10], [12, 16]]

Example 2

Input: insert_interval([], [5, 7])

Output: [[5, 7]]

Example 3

Input: insert_interval([[1, 3], [6, 9]], [2, 5])

Output: [[1, 5], [6, 9]]

Example 4

Input: insert_interval([[3, 5], [7, 9]], [1, 2])

Output: [[1, 2], [3, 5], [7, 9]]

Hints

Hint 1

Because the input list is already sorted and disjoint, you can process elements linearly in a single pass without re-sorting.

Hint 2

Divide the existing intervals into three groups relative to the insertion span: those entirely before it, those that overlap or touch it, and those entirely after it.

Hint 3

Maintain a single dynamic range `[start, end]` initialized to `new_interval`. As you iterate through overlapping intervals, update `start = min(start, cur_start)` and `end = max(end, cur_end)`.