19. Insert Interval
mediumAsked at BookingInsert a new booking window into a sorted list of non-overlapping reservations and merge any conflicts — exactly the operation Booking runs when a new reservation arrives on a partially-booked property calendar.
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, merging overlapping intervals as needed, and return the resulting array of non-overlapping intervals sorted by start.
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: [1,3] and [2,5] overlap and merge 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]]Approaches
1. Rebuild with merge pass
Collect all non-overlapping intervals before and after the new interval, then merge the middle group.
- Time
- O(n)
- Space
- O(n)
function insert(intervals, newInterval) {
const result = [];
let i = 0;
const n = intervals.length;
// Add all intervals that end before newInterval starts
while (i < n && intervals[i][1] < newInterval[0]) {
result.push(intervals[i++]);
}
// Merge all overlapping intervals with newInterval
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);
// Add remaining intervals
while (i < n) {
result.push(intervals[i++]);
}
return result;
}Tradeoff:
Booking-specific tips
Booking looks for disciplined boundary conditions: 'ends before' vs 'starts after'. Candidates who conflate strict vs non-strict inequality introduce silent overbooking bugs — make both checks explicit.
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →