Drill

ProblemsPython › dates

Find the first free slot in a day

harddatesPython

A scheduling assistant looks at a day of bookings and offers the earliest time a meeting of a given length would fit.

next_free_slot(busy: list<Slot>, day_start: int, day_end: int, minutes: int) → int?

Solve it in the editor →

Where you start

def next_free_slot(busy: list[Slot], day_start: int, day_end: int, minutes: int) -> int | None:
    

Worked examples

CallResult
next_free_slot([Slot(start=540, end=600)], 480, 1020, 30)480
next_free_slot([Slot(start=480, end=540)], 480, 1020, 30)540
next_free_slot([Slot(start=480, end=1020)], 480, 1020, 30)None
next_free_slot([Slot(start=540, end=600), Slot(start=610, end=700)], 480, 1020, 90)700

Hint

Sweep a cursor from the start of the day: before each booking, check whether the gap is wide enough, then jump the cursor past it.

Reference solution in Python
def next_free_slot(busy: list[Slot], day_start: int, day_end: int, minutes: int) -> int | None:
    if minutes <= 0:
        return None
    cursor = day_start
    for s in busy:
        if s.start - cursor >= minutes:
            return cursor
        if s.end > cursor:
            cursor = s.end
    return cursor if day_end - cursor >= minutes else None

The same problem in another language

More dates problems in Python