</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Insert Interval

Core idea: You're handed a list of intervals that is already sorted by start and already non-overlapping โ€” a tidy timeline with gaps between bookings โ€” plus one new interval to slot in. The new interval might land cleanly in a gap, or it might smother several existing intervals at once. The naive move is to dump it on the end, re-sort everything, and merge from scratch in O(n log n). But you're throwing away a gift: the input is already sorted. Exploit that and you never need to sort. Walk the list once in three phases โ€” (1) copy every interval that ends before the new one starts, untouched; (2) absorb every interval that overlaps the new one, growing new.start = min and new.end = max, then emit that single merged interval; (3) copy the rest, untouched. One linear pass, O(n) time, O(n) output.


The problem, rephrased

Imagine your day's calendar is a clean strip of booked time blocks, sorted left-to-right with daylight between them โ€” [[1,3], [6,9]]. A new request arrives: block off [2,5]. That request bleeds into the [1,3] booking and spills into the open gap, so the calendar should become [[1,5], [6,9]]. Your job: given intervals (sorted, non-overlapping) and one newInterval, insert it and merge any overlaps, returning a list that is still sorted and still non-overlapping.

This is LeetCode 57 โ€” Insert Interval.

Input intervals, newInterval What happens Output
[[1,3],[6,9]], [2,5] [2,5] overlaps [1,3], fills the gap before [6,9] [[1,5],[6,9]]
[[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8] [4,8] swallows [3,5], [6,7], [8,10] [[1,2],[3,10],[12,16]]
[[1,5]], [6,8] no overlap; [6,8] lands after everything [[1,5],[6,8]]
[], [5,7] nothing to merge [[5,7]]

The function returns a new list โ€” you can leave the input alone.


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.