Skip to content

ORIGINAL CODING QUESTION

Width after inserting a booking

A calendar holds closed, already-separated bookings sorted by start, where each booking starts after the previous one ends. A new closed booking [a, b] is added, and it merges with every booking it overlaps or shares an endpoint with, including bookings that only connect after earlier merges. Return the length (end - start) of the merged block that contains the new booking.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n pairs (start,end) sorted by start, then a and b.

Constraints

0 ≤ n ≤ 200; 0 ≤ start ≤ end ≤ 1000 for every booking; each start is greater than the previous end; 0 ≤ a ≤ b ≤ 1000.

Example 1

Input

3 1 2 4 6 9 12 5 9

Output

8

The new booking overlaps [4,6] and touches [9,12], forming [4,12] of length 8.

Example 2

Input

2 1 3 10 12 5 6

Output

1

The new booking connects to nothing, so its own length 1 is the answer.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Bookings entirely before or after the new one are untouched.

Hint 2

Sweep the sorted list, absorbing any booking that overlaps or touches the growing block.

Hint 3

Absorbing a booking can stretch the block start left or its end right.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →