Find the first free slot in a day
A scheduling assistant looks at a day of bookings and offers the earliest time a meeting of a given length would fit.
- All times are minutes since midnight. Bookings arrive sorted and do not overlap each other.
- The meeting must fit entirely between the start and end of the working day.
- A meeting may begin the moment a booking ends.
- A length of zero or less, or a day with no room, gives null.
NextFreeSlot(busy: list<Slot>, dayStart: int, dayEnd: int, minutes: int) → int?
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int? NextFreeSlot(List<Slot> busy, int dayStart, int dayEnd, int minutes) {
}
Worked examples
| Call | Result |
|---|---|
NextFreeSlot(new List<Slot> { new Slot(540, 600) }, 480, 1020, 30) | 480 |
NextFreeSlot(new List<Slot> { new Slot(480, 540) }, 480, 1020, 30) | 540 |
NextFreeSlot(new List<Slot> { new Slot(480, 1020) }, 480, 1020, 30) | null |
NextFreeSlot(new List<Slot> { new Slot(540, 600), new Slot(610, 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 C#
public int? NextFreeSlot(List<Slot> busy, int dayStart, int dayEnd, int minutes) {
if (minutes <= 0) return null;
int cursor = dayStart;
foreach (var s in busy) {
if (s.Start - cursor >= minutes) return cursor;
if (s.End > cursor) cursor = s.End;
}
return dayEnd - cursor >= minutes ? cursor : (int?) null;
}