Studio Booking Sheet

MediumintervalsAlso known as Insert Interval

A small recording studio keeps one booking sheet for its single room. Each line is a block of hours, like [13, 15] for 1 pm to 3 pm. The sheet is always tidy: blocks are in time order and no two blocks overlap or touch, because touching blocks get written as one.

A band calls to add a new block. Sometimes it fits in a gap; sometimes it overlaps one or more existing blocks, which then become one longer session. You need to rewrite the sheet so it is tidy again.

Your task

Write addBooking(bookings, newBooking). bookings is a list of [start, end] blocks sorted by start, with no two blocks overlapping or touching. newBooking is one [start, end] block. Return the new sheet: all blocks including the new one, sorted by start, with every group of overlapping or touching blocks combined into one.

Blocks that share only an endpoint count as touching: [10, 12] and [12, 14] become [10, 14]. Every block has start ≤ end. Return a new list; the input sheet may be empty.

addBooking(bookings: int[][], newBooking: int[]) → int[][]

Examples

Example 1
Input
bookings = [[9, 10], [13, 15], [18, 20]]
newBooking = [14, 19]
Output
[[9, 10], [13, 20]]
Why

[9, 10] ends before 14, so it stays as it is. [13, 15] overlaps the new block, and so does [18, 20]. All three together cover 13 to 20, so they become one session [13, 20].

Example 2
Input
bookings = [[9, 11], [16, 17]]
newBooking = [12, 14]
Output
[[9, 11], [12, 14], [16, 17]]
Why

The new block fits in the gap between 11 and 16 without touching either neighbour, so it is simply slotted in between them.

Constraints

  • 0 ≤ bookings.length ≤ 10,000
  • 0 ≤ start ≤ end ≤ 1,000,000,000
  • bookings is sorted, and for consecutive blocks a and b, a.end < b.start
Start with brute force

Append the new block to the list, then run a full merge: sort by start and sweep, combining overlapping blocks. It is correct and short.

But it costs O(n log n) for the sort and ignores that the sheet was already sorted and tidy. Only the new block is out of place, so one O(n) pass is enough.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code