← Whiteboard questions

Insert Interval

Insert a new interval into a sorted list and merge the overlaps

DSA, Medium, Intervals

Which structure or algorithm, and what does it cost.

A list ranges holds closed ranges [start, end], sorted by start. No two of them share a point. You also get one new range, new_range. Add it to the list. Where it overlaps ranges already there, merge them all into one. Ranges that share only an end point count as overlapping, so [1,4] and [4,7] become [1,7]. Return the new list, sorted by start, with no two ranges sharing a point.

Examples

Input ranges = [[2,5],[8,10],[14,18],[21,25]], new_range = [9,15]
Output [[2,5],[8,18],[21,25]]
Why the new range reaches [8,10] and [14,18], so the three become [8,18]. The others stay.
Input ranges = [[1,4],[10,12]], new_range = [4,7]
Output [[1,7],[10,12]]
Why the new range shares the point 4 with [1,4], so they merge.
Input ranges = [[3,5],[9,11]], new_range = [6,8]
Output [[3,5],[6,8],[9,11]]
Why the new range fits in the gap and touches nothing, so it is only placed in order.

Constraints

Your answer must contain

Target Aim for O(n) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

The list is already sorted. Which ranges can the new one never touch? Can you tell without merging anything?

Hint 2 the approach

Walk the list once. The ranges fall into three groups: those that end before the new one starts, those that touch it, and those that start after it ends.

Hint 3 the key step

While the next range starts at or before the new end, widen the new range to the smaller start and larger end. Then add it and copy the rest.

Walkthrough

Full walkthrough brute force to best

Brute force

Add the new range to the list, sort the list by start, then merge as in Merge Intervals. It is correct. It costs O(n log n) time because of the sort, and the sort ignores that the input is already in order.

Best method

The list is sorted and no two ranges share a point, so the ranges fall into three runs in order: those that end before the new range starts, those that touch it, and those that start after it ends. Copy the first run as it is. For the middle run, grow the new range to the smallest start and the largest end it meets, because the merged range must cover all of them. Add the grown range, then copy the last run. The run boundaries are exact: a range is in the first run only if its end is below the new start, so a range that ends exactly at the new start lands in the middle run, as the touching rule needs. Each range is looked at once.

Hand trace

Take ranges [[2,5],[8,10],[14,18],[21,25]] and new range [9,15]. [2,5] ends at 5, below 9, so copy it. [8,10] starts at 8, at most 15, so the new range becomes [8,15]. [14,18] starts at 14, at most 15, so it becomes [8,18]. [21,25] starts at 21, above 18, so the touching run is over. Add [8,18], then copy [21,25]. The result is [[2,5],[8,18],[21,25]].

Code

def insert_interval(ranges, new_range):
    s, e = new_range
    out = []
    i, n = 0, len(ranges)
    while i < n and ranges[i][1] < s:
        out.append(ranges[i])
        i += 1
    while i < n and ranges[i][0] <= e:
        s = min(s, ranges[i][0])
        e = max(e, ranges[i][1])
        i += 1
    out.append([s, e])
    out.extend(ranges[i:])
    return out

Time and memory

O(n) time, one pass with constant work per range. O(n) memory for the output list.

Common mistakes

  • Copying a range when its end is at most the new start. A range such as [1,4] with new range [4,7] shares the point 4, so it must merge. Copy only when its end is below the new start.
  • Setting the new end to the last merged range's end. If a middle range sits inside the new range, the end shrinks. Take the larger of the two ends.
  • Forgetting to add the new range when it comes after every range, or when the list is empty. Add it right after the middle loop, every time.

Related problems

More Intervals problems
Insert Interval: hints, walkthrough and Python solution