Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Intervals

Fewest bookings to cancel so none overlap

Medium · Target 18 minutes · Intervals · Type asked atGoogleAmazon

Each booking is a pair [start, end] with start < end. Two bookings clash if they share any time; bookings that only touch, like [1, 2] and [2, 3], do not clash. Return the smallest number of bookings to cancel so that none of the remaining ones clash.

Examples

InputOutputWhy
bookings = [[1, 2], [2, 3], [3, 4], [1, 3]]1Cancel [1, 3]; the other three run back to back.
bookings = [[1, 2], [1, 2], [1, 2]]2Only one copy can stay.
bookings = [[1, 10], [2, 3], [4, 5], [6, 7]]1Cancelling the long one keeps three.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −5·10⁴ ≤ start < end ≤ 5·10⁴

Hints

Hint 1

Turn it round: cancelling the fewest is the same as keeping the most. Which booking should you keep first?

Hint 2

Of all the bookings, keep the one that finishes earliest. Why can that choice never be worse than any other?

Hint 3

Sort by end time. Keep a booking if it starts no earlier than the end of the last one you kept; otherwise cancel it.

Where people lose marks

  • Sorting by start time: a long booking that starts first crowds out several short ones.
  • Treating touching bookings as clashing, which cancels one booking too many.
  • Keeping the shortest bookings first: a short booking in the middle can clash with two that would otherwise fit.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.