Skip to content
mlmentorship

Insert Interval

Insert one range into sorted, non-overlapping ranges and merge when needed.

Published · 8 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Insert Interval

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Start-sorted, pairwise disjoint closed integer intervals and one closed new_interval = [start, end]. Output. Return a start-sorted disjoint list covering exactly the old intervals and the new interval together. Rules. Every interval has start <= end. Overlapping intervals and intervals sharing an endpoint must merge. Do not change either input. The reference may reuse untouched input rows in the output rather than copying them. With no old intervals, return the new interval's values as the only interval. Example. Inserting [2, 5] into [[1, 3], [6, 9]] returns [[1, 5], [6, 9]]. Inserting [3, 6] into the same list returns [[1, 9]] because both endpoints connect.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Partition sorted ranges into a copied prefix, one growing overlap span, and an untouched suffix.

Problem trace

Grow the overlapping span; leave the first separated interval untouched

Worked example: merge the overlap but stop before the first separated intervalInserting (2,5) into (1,3),(6,9) merges only the first interval. The separated (6,9) stays unchanged.Overlap extends the active endpoint;separated spans surviveNew [2,5] lies between the sortedneighbors[1,3][2,5][6,9]Merge the overlap; preserve separated[6,9][1,5][6,9]Final union: [1,5], [6,9]
Read it this way: Inserting (2,5) into (1,3),(6,9) merges only the first interval. The separated (6,9) stays unchanged. What gap prevents interval six-to-nine from entering the first merged span?
Full interview answer 8 min read
Reading depth

Insert one interval into an ordered disjoint interval list and return the resulting merged coverage.

Problem

Input. Start-sorted, pairwise disjoint closed integer intervals and one closed new_interval = [start, end].

Output. Return a start-sorted disjoint list covering exactly the old intervals and the new interval together.

Rules. Every interval has start <= end. Overlapping intervals and intervals sharing an endpoint must merge. Do not change either input. The reference may reuse untouched input rows in the output rather than copying them. With no old intervals, return the new interval’s values as the only interval.

Example. Inserting [2, 5] into [[1, 3], [6, 9]] returns [[1, 5], [6, 9]]. Inserting [3, 6] into the same list returns [[1, 9]] because both endpoints connect.

Picture

Inserting [4,8] into [[1,2],[3,5],[6,7],[8,10],[12,16]] keeps [1,2], grows [3,10], then reuses [12,16].

Problem trace

Grow the overlapping span; leave the first separated interval untouched

Input and goalInsert one range into sorted, non-overlapping ranges and merge when needed.
Initialize the inserted rangeUse intervals [[1,2],[3,5],[6,7],[8,10],[12,16]] and new [4,8]. Start answer = [], index = 0, span = [4,8].
current [1,2]
[3,5]
new span [4,8]
[6,7]
[8,10]
[12,16]
stateanswer = []; span = [4,8]
max
16
state
answer = []; span = [4,8]
index 0
current [1,2]

Recognize it
Use it when inserting one range into already sorted disjoint ranges; their order partitions them into intervals ending before, overlapping, or starting after the growing span.
Keep true
answer contains every interval strictly before the span, span is the union of the new interval and all consumed overlaps, and intervals from index onward remain untouched and sorted.
Reuse it
When ordered input surrounds one mutable object, scan an immutable prefix, absorb the contiguous interaction region into that object, then reuse the untouched suffix.
Use intervals [[1,2],[3,5],[6,7],[8,10],[12,16]] and new [4,8]. Start answer = [], index = 0, span = [4,8]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does [8,10] merge into the span while [12,16] remains untouched?
Reference drawing

Problem trace

Grow the overlapping span; leave the first separated interval untouched

Worked example: merge the overlap but stop before the first separated intervalInserting (2,5) into (1,3),(6,9) merges only the first interval. The separated (6,9) stays unchanged.Overlap extends the active endpoint;separated spans surviveNew [2,5] lies between the sortedneighbors[1,3][2,5][6,9]Merge the overlap; preserve separated[6,9][1,5][6,9]Final union: [1,5], [6,9]
Execution trace
Input and goalInsert one range into sorted, non-overlapping ranges and merge when needed.
Initialize the inserted rangeUse intervals [[1,2],[3,5],[6,7],[8,10],[12,16]] and new [4,8]. Start answer = [], index = 0, span = [4,8].
current [1,2]
[3,5]
new span [4,8]
[6,7]
[8,10]
[12,16]
stateanswer = []; span = [4,8]
max
16
state
answer = []; span = [4,8]
index 0
current [1,2]

Recognize it
Use it when inserting one range into already sorted disjoint ranges; their order partitions them into intervals ending before, overlapping, or starting after the growing span.
Keep true
answer contains every interval strictly before the span, span is the union of the new interval and all consumed overlaps, and intervals from index onward remain untouched and sorted.
Reuse it
When ordered input surrounds one mutable object, scan an immutable prefix, absorb the contiguous interaction region into that object, then reuse the untouched suffix.
Use intervals [[1,2],[3,5],[6,7],[8,10],[12,16]] and new [4,8]. Start answer = [], index = 0, span = [4,8]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does [8,10] merge into the span while [12,16] remains untouched?
Read it this way: Inserting (2,5) into (1,3),(6,9) merges only the first interval. The separated (6,9) stays unchanged. What gap prevents interval six-to-nine from entering the first merged span?

The prefix ends before start; every subsequent overlapping row can only expand end. Once the next start exceeds end, sorted disjointness makes the entire suffix safe. This is interval union without resorting already ordered input.

Code

def insert_interval(intervals: list[list[int]], new_interval: list[int]) -> list[list[int]]:
   answer: list[list[int]] = []
   index = 0
   start, end = new_interval

   while index < len(intervals) and intervals[index][1] < start:
      answer.append(intervals[index])
      index += 1

   while index < len(intervals) and intervals[index][0] <= end:
      start = min(start, intervals[index][0])
      end = max(end, intervals[index][1])
      index += 1

   return answer + [[start, end]] + intervals[index:]

Cost: time and answer space.

Slicing and concatenation also allocate temporary references. Integer comparisons count as constant-cost operations.

Change the Requirement

Detach the Result

New task: Prevent result-row mutations from affecting either input.

Picture and change: Copy every row after computing the same union.

Code: Reuse the complete reference.

def insert_interval_copy(intervals: list[list[int]], new_interval: list[int]):
   return [row[:] for row in insert_interval(intervals, new_interval)]

Check: Inserting [5,6] into [[1,2]] returns [[1,2],[5,6]] with fresh row objects.

Use when: Callers need independent ownership; time and storage remain linear.

Exclude Right Endpoints

New task: Keep touching half-open intervals separate; require positive durations.

Picture and change: The prefix accepts end <= start; merging requires next_start < end.

Code: Existing rows must be sorted and nonoverlapping under the half-open convention.

def insert_half_open(intervals: list[list[int]], new_interval: list[int]):
   answer, index = [], 0
   start, end = new_interval
   while index < len(intervals) and intervals[index][1] <= start:
      answer.append(intervals[index])
      index += 1
   while index < len(intervals) and intervals[index][0] < end:
      start = min(start, intervals[index][0])
      end = max(end, intervals[index][1])
      index += 1
   return answer + [[start, end]] + intervals[index:]

Check: insert_half_open([[1,3]], [3,5]) returns [[1,3],[3,5]]; the closed reference returns [[1,5]].

Use when: An endpoint touch is not a merging event. The aliasing and linear bounds remain unchanged.

Reconstruct

Why not accept arbitrary unsorted rows?

Reasoned answer

With [[8,10],[1,2]] and [3,4], the first row already looks like a safe suffix. The reference never discovers the later earlier interval, so its result is not sorted. Sort and merge arbitrary input first; the linear proof depends on the original ordering and disjointness.