Python coding

Fewest bookings to cancel

Each booking of a single room is a pair [start, end] with start < end. Two bookings clash when their times overlap; one that starts exactly when another ends does not clash. Return the fewest bookings you must cancel so that no two of the remaining ones clash.

The list is not sorted, may be empty and may contain identical bookings.

Besides the tests, one large input (4,000 bookings) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • min_cancellations([[1,3],[2,4],[3,5]]) → 1
  • min_cancellations([[1,10],[2,3],[4,5],[6,7]]) → 1
  • min_cancellations([[1,2],[2,3],[3,4]]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Flip the question: cancelling the fewest means keeping the most bookings that don't clash. That is a greedy choice after a sort.

Hint 2

Sort by end time. Keep a booking if it starts at or after the end of the last one you kept; otherwise cancel it.

Hint 3

Sorting by start is the trap: [1, 10] comes first and blocks [2, 3], [4, 5] and [6, 7]. The booking that ends earliest leaves the most room.

Solution and why it works
pythonO(n log n) · O(n)
def min_cancellations(bookings: list[list[int]]) -> int:
    kept = 0
    free_at = float("-inf")                  # when the room is free again
    for start, end in sorted(bookings, key=lambda b: b[1]):
        if start >= free_at:                 # back-to-back bookings don't clash
            kept += 1
            free_at = end
    return len(bookings) - kept

Cancelling the fewest is keeping the most. Among the bookings that can still fit, the one that ends earliest leaves the most room for the rest, so sorting by end and keeping every booking that starts once the room is free is optimal: O(n log n). Sorting by start fails: [1, 10] would block three short bookings. Use >= for the check, since a booking may start exactly when the previous one ends.