57. Insert Interval
mediumAsked at AirbnbSplice a new booking into a sorted availability list without disturbing existing reservations — Airbnb's calendar service does this on every Instant Book confirmation that lands between two blocked windows.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an array of non-overlapping intervals sorted by start time and a new interval. Insert the new interval and merge any overlapping ones, returning the resulting sorted array of non-overlapping intervals.
Constraints
0 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^5intervals is sorted in ascending order by start_inewInterval.length == 2
Examples
Example 1
intervals = [[1,3],[6,9]], newInterval = [2,5][[1,5],[6,9]]Explanation: The new interval [2,5] overlaps [1,3] and merges into [1,5].
Example 2
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8][[1,2],[3,10],[12,16]]Explanation: [4,8] overlaps [3,5], [6,7], and [8,10], merging them into [3,10].
Approaches
1. Brute force (append and re-merge)
Append the new interval, then run the full Merge Intervals sort-and-sweep. Correct but wastes the fact that the input is already sorted.
- Time
- O(n log n)
- Space
- O(n)
function insert(intervals, newInterval) {
const all = [...intervals, newInterval].sort((a, b) => a[0] - b[0]);
const merged = [all[0]];
for (let i = 1; i < all.length; i++) {
const last = merged[merged.length - 1];
if (all[i][0] <= last[1]) {
last[1] = Math.max(last[1], all[i][1]);
} else {
merged.push(all[i]);
}
}
return merged;
}Tradeoff:
2. Single-pass linear insert
Three-phase sweep: copy all intervals that end before newInterval starts, merge all that overlap, then copy the rest. Exploits sorted order for O(n) time.
- Time
- O(n)
- Space
- O(n)
function insert(intervals, newInterval) {
const result = [];
let i = 0;
const n = intervals.length;
while (i < n && intervals[i][1] < newInterval[0]) {
result.push(intervals[i++]);
}
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
while (i < n) result.push(intervals[i++]);
return result;
}Tradeoff:
Airbnb-specific tips
Interviewers at Airbnb often give this right after Merge Intervals to see if you can exploit the sorted guarantee. Explicitly state the three phases before coding — they want to hear that you recognize no sorting is needed. Common trap: off-by-one on the overlap boundary conditions (use strict < for ends-before and <= for starts-after-merge).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Insert Interval and other Airbnb interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →