Drill

ProblemsGo › dates

Find the first free slot in a day

harddatesIntervalsSortingGreedyGo

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?

Go 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.

Solve it in Python →

Where you start

func nextFreeSlot(busy []Slot, dayStart int, dayEnd int, minutes int) *int {
	
}

Worked examples

CallResult
nextFreeSlot([]Slot{Slot{Start: 540, End: 600}}, 480, 1020, 30)pInt(480)
nextFreeSlot([]Slot{Slot{Start: 480, End: 540}}, 480, 1020, 30)pInt(540)
nextFreeSlot([]Slot{Slot{Start: 480, End: 1020}}, 480, 1020, 30)nil
nextFreeSlot([]Slot{Slot{Start: 540, End: 600}, Slot{Start: 610, End: 700}}, 480, 1020, 90)pInt(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 Go
func nextFreeSlot(busy []Slot, dayStart int, dayEnd int, minutes int) *int {
	if minutes <= 0 {
		return nil
	}
	cursor := dayStart
	for _, s := range busy {
		if s.Start-cursor >= minutes {
			return &cursor
		}
		if s.End > cursor {
			cursor = s.End
		}
	}
	if dayEnd-cursor >= minutes {
		return &cursor
	}
	return nil
}

The same problem in another language

More dates problems in Go