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

Total time covered by a set of bookings

Easy · Target 12 minutes · Intervals · Type asked atBloombergAmazon

Each booking is a pair [start, end] of integers with start < end, covering the time from start up to end. Bookings may overlap, touch or nest inside one another, and they are not in any particular order. Return the total length of time covered by at least one booking.

Examples

InputOutputWhy
bookings = [[1, 3], [2, 6], [8, 10]]71 to 6 is covered once the first two merge (5), plus 8 to 10 (2).
bookings = [[1, 4], [4, 5]]4Touching bookings cover 1 to 5 without a gap.
bookings = [[1, 10], [2, 3], [4, 5]]9The short bookings sit inside the long one and add nothing.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ start < end ≤ 10⁹

Hints

Hint 1

Adding up every booking's length double-counts the overlaps. What order would let you see each overlap the moment it happens?

Hint 2

Sort by start time. A booking that starts after everything so far has ended begins a new block; otherwise it can only extend the current one.

Hint 3

Keep the current block's start and end. On a gap, add the block's length to the total and start a new block. Add the last block at the end.

Where people lose marks

  • Summing every booking's length: overlaps are counted twice.
  • Setting end = e instead of end = max(end, e): a booking nested inside the block would shorten it.
  • Forgetting the last block, which is never followed by a gap.
  • Sorting by end time: two bookings far apart can then sit next to each other while an overlapping one comes later.
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.