Insert Interval solution explained
To insert an interval into a sorted list of non-overlapping intervals, make one pass in three phases: copy every interval that ends before the new one starts, absorb every interval that overlaps it by widening the new interval's bounds, then copy the rest. Because the input is already sorted and disjoint, no sort is needed and the whole thing runs in O(n) time.
By Evin JohnPublished 8 min read
The problem, reworded
You hold a calendar of busy blocks, each a [start, end] pair. The blocks are sorted by start and none of them overlap. A new block arrives. Add it so the calendar stays sorted and overlap-free: if the new block touches or overlaps existing ones, they all become a single block covering the lot. Return the updated list.
| New range | Result | What happened |
|---|---|---|
[5, 10] | [[1, 2], [4, 11], [14, 15]] | Overlaps [4, 6] and [9, 11], which merge with it |
[12, 13] | [[1, 2], [4, 6], [9, 11], [12, 13], [14, 15]] | Fits in a gap, nothing merges |
[2, 4] | [[1, 6], [9, 11], [14, 15]] | Touches [1, 2] at 2 and [4, 6] at 4, so all three join |
[15, 17] | [[1, 2], [4, 6], [9, 11], [14, 17]] | Touches the last range at 15 and extends it |
[0, 20] | [[0, 20]] | Swallows every existing range |
These examples treat ranges as closed, so sharing an endpoint counts as overlapping, matching the convention on the Merge Intervals page. With half-open calendar slots, [1, 2] and [2, 4] would stay separate. Ask which one the interviewer wants, and whether you may change the input list or should return a new one.
What this round is looking for
Insert Interval rewards candidates who use what they are given. The input is sorted and disjoint, and a candidate who sorts it again has missed the main clue. Interviewers also watch how you handle the boundaries between the three phases: the comparison operators are where off-by-one bugs live, and saying why each one is strict or not is part of the answer.
The simple version: append, then merge everything
Add the new range to the list, sort by start, and run the standard sort-then-sweep merge. It is correct and quick to write, and it is a perfectly good first sentence in the interview. Its cost is O(n log n) for the sort, and it throws away the fact that the list was already in order. Mention it, then improve it. The merge code itself is on the Merge Intervals page.
One pass in three phases
- Copy the ranges that finish too earlyWhile the current range ends strictly before the new range starts, it cannot touch the new range. Copy it unchanged and move on.
- Absorb the ranges that overlapWhile the current range starts at or before the new range's end, the two meet. Widen the new range to the smaller start and the larger end, and skip the old range. Because the list is sorted, the overlapping ranges form one consecutive run.
- Place the new range, then copy the restAppend the widened new range. Every range left starts after it ends, so copy them unchanged.
def place_range(ranges, new):
lo, hi = new
out = []
k = 0
# 1. ranges that finish before the new one begins
while k < len(ranges) and ranges[k][1] < lo:
out.append(list(ranges[k]))
k += 1
# 2. ranges that touch or overlap it: absorb them
while k < len(ranges) and ranges[k][0] <= hi:
lo = min(lo, ranges[k][0])
hi = max(hi, ranges[k][1])
k += 1
out.append([lo, hi])
# 3. ranges that begin after it ends
while k < len(ranges):
out.append(list(ranges[k]))
k += 1
return outfunction placeRange(ranges, newRange) {
let [lo, hi] = newRange;
const out = [];
let k = 0;
while (k < ranges.length && ranges[k][1] < lo) {
out.push([ranges[k][0], ranges[k][1]]);
k++;
}
while (k < ranges.length && ranges[k][0] <= hi) {
lo = Math.min(lo, ranges[k][0]);
hi = Math.max(hi, ranges[k][1]);
k++;
}
out.push([lo, hi]);
while (k < ranges.length) {
out.push([ranges[k][0], ranges[k][1]]);
k++;
}
return out;
}Trace: inserting [5, 10]
Phase 1: [1, 2] ends at 2, which is before 5, so it is copied. [4, 6] ends at 6, not before 5, so phase 1 stops. Phase 2: [4, 6] starts at 4, which is at or before 10, so the new range becomes [4, 10]. [9, 11] starts at 9, still at or before 10, so it becomes [4, 11]. [14, 15] starts at 14, after 11, so phase 2 stops and [4, 11] is appended. Phase 3 copies [14, 15].
Look at the two comparisons. Phase 1 uses ends strictly before the new start, and phase 2 uses starts at or before the new end. Both choices follow from closed ranges: a range ending exactly at the new start shares a point with it and must be absorbed. For half-open ranges, flip both: copy while end is at or before the new start, absorb while start is strictly before the new end.
Finding the middle block with binary search
If the list is long and you only need to locate the overlap, binary search finds it. The ends are sorted too, since the ranges are disjoint and sorted by start. The first overlapping range is the first one whose end is at least the new start, and the overlap stops at the last range whose start is at most the new end. The search takes O(log n), but assembling the output list is still O(n). With a balanced search tree or a sorted container that supports deletion, the update becomes O(log n) plus the number of ranges removed, which matters if inserts keep arriving.
from bisect import bisect_left, bisect_right
def place_range_bisect(ranges, new):
lo, hi = new
ends = [r[1] for r in ranges]
starts = [r[0] for r in ranges]
first = bisect_left(ends, lo) # first range that ends at or after lo
stop = bisect_right(starts, hi) # ranges from here on start after hi
if first < stop:
lo = min(lo, ranges[first][0])
hi = max(hi, ranges[stop - 1][1])
return [list(r) for r in ranges[:first]] + [[lo, hi]] + [list(r) for r in ranges[stop:]]Complexity
| Approach | Time | Extra space |
|---|---|---|
| Append, sort, merge | O(n log n) | O(n) |
| Three-phase sweep | O(n) | O(n) for the output |
| Binary search, then splice | O(log n) to locate, O(n) to rebuild | O(n) |
| Balanced tree or sorted container, many inserts | O(log n + removed ranges) per insert | O(n) total |
Edge cases
- An empty list: the answer is just the new range.
- The new range lies entirely before the first range or after the last one: phases 1 or 3 copy everything.
- The new range sits inside one existing range: phase 2 absorbs that one range and the bounds do not change.
- The new range covers every existing range: phase 2 absorbs them all.
- A zero-length new range such as [3, 3] that fits in a gap is inserted as its own entry.
Mistakes to avoid
- Re-sorting a list that is already sorted, which signals you did not read the input guarantee.
- Updating only the end in phase 2. The new range may start inside an earlier range, so its start must take the minimum too.
- Appending the new range inside phase 2 instead of after it, which produces duplicates.
- Forgetting to append the new range at all when it lands after every existing range.
- Mixing closed and half-open comparisons between phase 1 and phase 2, which leaves touching ranges unmerged or merges ranges with a gap between them.
Follow-up questions
- Remove a range instead of adding one. Walk the list; ranges that overlap the removed one may be cut down or split in two.
- Insert many ranges, one at a time. Use a sorted structure so each insert is logarithmic, as described above.
- Is the new meeting free of conflicts? That is a yes-or-no version of phase 2 and leads to Meeting Rooms.
- Make the list overlap-free by deleting, not merging. That is Non-overlapping Intervals, a greedy problem with a different goal.
Explaining your approach
Fictional example
- Candidate
- I could append and re-merge, but that sorts again. The input is already sorted and disjoint, so I'll use that.
- Candidate
- The ranges split into three runs: those ending before my new start, those overlapping it, and those starting after my new end. I copy the first run, widen my new range over the second, append it, then copy the third.
- Candidate
- That's linear. I'm treating shared endpoints as overlap; for half-open slots I'd flip both comparisons.
Related walkthroughs
Merge Intervals handles an unsorted list from scratch. Meeting Rooms asks whether a schedule has any overlap at all, and Non-overlapping Intervals asks how few ranges you must delete to remove every overlap. The coding problems hub groups them by pattern.
Practice with Natively
When practicing on Mac or Windows, you can point Natively at this problem through a screenshot and ask it to poke holes in your phase boundaries, for example with a range that only touches its neighbor. It transcribes the whole mock session and stores notes, so you can review whether you stated the closed or half-open choice before coding. The AI interview assistant page explains more.
Questions people ask
How do you solve Insert Interval?
Walk the sorted list in three phases: copy ranges that end before the new one starts, widen the new range over every range that overlaps it, append it, then copy the remaining ranges.
What is the time complexity of Insert Interval?
O(n), because the input is already sorted and disjoint. Appending and re-merging also works but costs O(n log n) for the sort.
Can binary search speed up Insert Interval?
It finds the overlapping run in O(log n), but building the new list is still O(n). With a balanced tree or sorted container, each insert becomes logarithmic plus the ranges removed.
Should touching intervals merge in Insert Interval?
With closed ranges, yes, since they share a point. With half-open time slots, no. Ask which one applies, then flip both phase comparisons if needed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
