Drill

ProblemsTypeScript › dates

Find the first free slot in a day

harddatesTypeScript

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

nextFreeSlot(busy: list<Slot>, dayStart: int, dayEnd: int, minutes: int) → int?

Solve it in the editor →

Where you start

function nextFreeSlot(busy: Slot[], dayStart: number, dayEnd: number, minutes: number): number | null {
  
}

Worked examples

CallResult
nextFreeSlot([{"start":540,"end":600}], 480, 1020, 30)480
nextFreeSlot([{"start":480,"end":540}], 480, 1020, 30)540
nextFreeSlot([{"start":480,"end":1020}], 480, 1020, 30)null
nextFreeSlot([{"start":540,"end":600},{"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 TypeScript
function nextFreeSlot(busy: Slot[], dayStart: number, dayEnd: number, minutes: number): number | null {
  if (minutes <= 0) return null;
  let cursor = dayStart;
  for (const s of busy) {
    if (s.start - cursor >= minutes) return cursor;
    if (s.end > cursor) cursor = s.end;
  }
  return dayEnd - cursor >= minutes ? cursor : null;
}

The same problem in another language

More dates problems in TypeScript