KatInterview

Booked Time and Peak Room Demand for a Schedule

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweep-linesorting

Last updated

Compute the total time covered by a set of half-open intervals and the maximum number of simultaneously active intervals, ignoring empty or reversed ones.

Booked Time and Peak Room Demand

A calendar holds a list of bookings. Each booking is a pair (start, end) of integers describing the half-open time range [start, end): the booking occupies start but not end.

Write a function that returns two numbers as a pair (covered, rooms):

  1. covered: the total length of time during which at least one booking is active. Time where several bookings overlap is counted only once.
  2. rooms: the smallest number of rooms that lets every booking take place as scheduled, which equals the largest number of bookings active at the same moment.

Rules

  • A booking with start >= end has no duration. It must be ignored completely and affects neither value.
  • Because ranges are half-open, two bookings that merely touch do not overlap. For example, (1, 3) and (3, 5) can share one room.
  • The input may be in any order and may contain duplicates.
  • If no valid booking remains (including an empty list), return (0, 0).

Input

  • intervals: a list of (start, end) pairs of integers.

Output

  • A pair (covered, rooms) of integers.

Constraints

  • The number of bookings n may be zero or larger; an O(n log n) solution is expected.
  • Start and end values are integers and may be negative or zero.
  • Bookings with start >= end are possible and must be ignored.
  • The list is not guaranteed to be sorted.

Examples

Example 1

Input: booked_time_and_rooms([[1, 4], [2, 5], [7, 9]])

Output: [6, 2]

Example 2

Input: booked_time_and_rooms([[1, 3], [3, 5]])

Output: [4, 1]

Example 3

Input: booked_time_and_rooms([[2, 2], [4, 4], [-1, -1]])

Output: [0, 0]

Hints

Hint 1

The two answers need different ideas: one is about the union of the ranges, the other about the deepest overlap at any single moment.

Hint 2

For the covered time, sort by start and merge ranges, extending the current block's end with a max whenever the next range begins no later than that end.

Hint 3

For the rooms, create +1 events at starts and -1 events at ends, and sort so that at equal times the -1 comes first. The peak running total is the answer.