Gift delivery scheduler with limited agents
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests greedy, heap and scheduling.
You are planning gift deliveries to employees in an office. The workday runs from hour 9 to hour 17.
You get:
-
intervals, a list of[start, end]pairs with integer hours. Employeeiis in the office fromstart_iuntilend_i. -
n, the number of delivery agents.
Rules:
- A delivery takes exactly one hour and must start on a whole hour.
- A delivery to employee
ithat starts at hourhis allowed only ifstart_i <= handh + 1 <= end_i. - Each agent makes at most one delivery per hour, so at most
ndeliveries can happen in the same hour. - Each employee gets at most one gift.
Implement schedule_deliveries(intervals, n). Return the largest number of employees who can get their gift, and a schedule that achieves it: for each employee, the start hour of their delivery, or None if they are not served.
Constraints: 0 <= len(intervals) <= 10^5, 9 <= start <= end <= 17, 0 <= n <= 10^5. Aim for better than trying all assignments.
Example 1
intervals = [[9, 11], [9, 10], [9, 10]], n = 1
-> 2
Only one agent works. One of the two employees who leave at 10 gets the 9:00 slot, and the employee who stays until 11 gets the 10:00 slot. The other early leaver misses out.
Example 2
intervals = [[9, 12], [10, 11], [9, 10]], n = 1
-> 3 schedule: [11, 10, 9]
Serve whoever leaves first: [9, 10] at 9:00, [10, 11] at 10:00, and [9, 12] at 11:00.
Clarifying questions
- Is an employee with
start == endnever servable? - With
n = 0, is the answer 0 with every entryNone? - Is any maximum schedule accepted, or a specific one?
What a strong answer covers
- Goes hour by hour from 9 to 16, adding employees whose
start <= hto a min-heap byend. - Each hour pops expired employees (
end < h + 1) and serves up tonof the rest with the earliestend. - Justifies earliest-deadline-first with an exchange argument: swapping a later leaver for an earlier one never reduces the count.
- Runs in O(m log m) for m employees; with only 8 hours, sorting by start and using the heap is plenty.
- Tests both examples,
n = 0, more agents than employees, and employees with no valid hour.
Follow-ups
- Deliveries take different lengths of time.
- Each employee has a priority or value: maximise the total value served.
- Agents have their own working hours.
Where it's asked
What it tests
greedy · heap · scheduling · intervals
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
