Drill

ProblemsC++ › dates

Find the first free slot in a day

harddatesIntervalsSortingGreedyC++

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?

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.

Solve it in Python →

Where you start

std::optional<int> nextFreeSlot(std::vector<Slot> busy, int dayStart, int dayEnd, int minutes) {
    
}

Worked examples

CallResult
nextFreeSlot(std::vector<Slot>{Slot{540, 600}}, 480, 1020, 30)std::optional<int>(480)
nextFreeSlot(std::vector<Slot>{Slot{480, 540}}, 480, 1020, 30)std::optional<int>(540)
nextFreeSlot(std::vector<Slot>{Slot{480, 1020}}, 480, 1020, 30)std::nullopt
nextFreeSlot(std::vector<Slot>{Slot{540, 600}, Slot{610, 700}}, 480, 1020, 90)std::optional<int>(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++
std::optional<int> nextFreeSlot(std::vector<Slot> busy, int dayStart, int dayEnd, int minutes) {
    if (minutes <= 0) return std::nullopt;
    int cursor = dayStart;
    for (const auto& s : busy) {
        if (s.start - cursor >= minutes) return cursor;
        if (s.end > cursor) cursor = s.end;
    }
    if (dayEnd - cursor >= minutes) return cursor;
    return std::nullopt;
}

The same problem in another language

More dates problems in C++