← Questions

Gift delivery scheduler with limited agents

0
MicrosoftCoding

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. Employee i is in the office from start_i until end_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 i that starts at hour h is allowed only if start_i <= h and h + 1 <= end_i.
  • Each agent makes at most one delivery per hour, so at most n deliveries 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 == end never servable?
  • With n = 0, is the answer 0 with every entry None?
  • 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 <= h to a min-heap by end.
  • Each hour pops expired employees (end < h + 1) and serves up to n of the rest with the earliest end.
  • 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding