34/42
Part 8 of 8 · Follow-upsLearn and do

What interviewers ask next

Bookings that arrive one at a time: bisect finds the only two that can clash

A booking calendar accepts a booking only if it overlaps none already taken. Keep the starts and the ends in two sorted lists:

from bisect import bisect_right


class Calendar:
    def __init__(self):
        self.starts, self.ends = [], []

    def book(self, start, end):
        i = bisect_right(self.starts, start)
        # the one before runs past our start
        if i > 0 and self.ends[i - 1] > start:
            return False
        # the next one starts before we end
        if i < len(self.starts) and self.starts[i] < end:
            return False
        self.starts.insert(i, start)
        self.ends.insert(i, end)
        return True


calendar = Calendar()
tries = [(10, 20), (15, 25), (20, 30), (5, 10), (9, 11), (30, 31), (25, 26)]
print([calendar.book(start, end) for start, end in tries])
[True, False, True, True, False, True, False]

Kept bookings never overlap each other. So a new booking can only clash with its neighbors in start order: the one just before it and the one just after. bisect_right finds its place, and two comparisons decide. Here is the last call, (25, 26), where bisect_right returns 3:

A new booking, (25, 26), between its neighbors
0: (5, 10)
1: (10, 20)
2: (20, 30) i - 1: ends after 25
3: (30, 31) i: starts after 26
new (25, 26)
51015202530

Booking 2 runs past 25, so (25, 26) is refused. The class matched a scan of every kept booking on 300 random runs.

The search is O(log n), and the insert is O(n) because the list shifts. That's the insort cost from the sorting and binary search lesson. For a calendar that also merges, use insert from the merge section. For many writes at scale, a balanced search tree keeps both at O(log n).

In the editor, STARTS and ENDS are the kept bookings from the figure, in start order. Write the rest of clash_with(starts, ends, start, end): the neighbor the new booking overlaps, or None.