Hourly Agent Call Scheduler

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build a task assignment function schedule_tasks(tasks, max_concurrency, agents) for an inbound/outbound phone support platform operating on discrete one-hour blocks.

You receive: - tasks: a list of dictionaries, each describing a scheduled phone session with keys: - 'task_id' (int): unique identifier for the session, - 'customer_id' (int): identifier of the client organization or caller, - 'start_time' (int): starting hour of the session, - 'duration' (int): length of the session in whole hours. - max_concurrency (int): maximum number of simultaneous sessions any single customer_id is allowed to have running during the same hour. - agents (List[int]): integer identifiers of the support agents available for assignment (if an identifier is listed more than once, it still represents the same single person).

Every session occupies the half-open time span [start_time, start_time + duration) and its start_time is fixed. Time advances linearly without wrapping around at hour 24 (for instance, a session starting at hour 23 with duration = 3 spans [23, 26) and does not collide with [0, 2)). A valid schedule must satisfy three rules:

  1. Single-task agent capacity: An agent can handle at most one session during any hour.
  2. Uninterrupted coverage: One agent must stay on a session for its entire [start_time, start_time + duration) window. Because intervals are half-open, a session ending at hour h frees both its agent and its customer slot in time for another session starting at hour h.
  3. Per-customer concurrency cap: During every hour, each customer may have at most max_concurrency active sessions.

Return a dictionary {task_id: agent_id} assigning every session in tasks to an agent from agents (if multiple valid assignments exist, any valid one is accepted). If no valid full assignment exists, return {}.

Examples

Example 1

tasks = [
    {"task_id": 10, "customer_id": 500, "start_time": 2, "duration": 3},
    {"task_id": 20, "customer_id": 500, "start_time": 4, "duration": 2},
    {"task_id": 30, "customer_id": 600, "start_time": 5, "duration": 3},
]
max_concurrency = 2
agents = [41, 42]

Output:

{10: 41, 20: 42, 30: 41}

Explanation: Session 10 covers [2, 5) and session 20 covers [4, 6). Both belong to customer 500 and overlap during hour 4, reaching 2 simultaneous sessions (<= max_concurrency). Agent 41 handles [2, 5), agent 42 handles [4, 6), and as soon as hour 5 begins, agent 41 is free to pick up session 30 on [5, 8).

Example 2

tasks = [
    {"task_id": 10, "customer_id": 500, "start_time": 2, "duration": 3},
    {"task_id": 20, "customer_id": 500, "start_time": 4, "duration": 2},
]
max_concurrency = 1
agents = [41, 42]

Output:

{}

Explanation: Even though two agents are free, customer 500 has two sessions active at hour 4, exceeding max_concurrency = 1.

Example 3

tasks = [
    {"task_id": 7, "customer_id": 301, "start_time": 9, "duration": 4},
    {"task_id": 8, "customer_id": 302, "start_time": 10, "duration": 2},
    {"task_id": 9, "customer_id": 303, "start_time": 11, "duration": 3},
]
max_concurrency = 1
agents = [41, 42]

Output:

{}

Explanation: Every customer has only one session, so max_concurrency = 1 is satisfied. However, [9, 13), [10, 12), and [11, 14) are all active during hour 11, requiring three distinct agents when only two are available.

Constraints

  • 1 <= len(tasks) <= 1000
  • 0 <= start_time < 24
  • 1 <= duration <= 24
  • 0 <= max_concurrency <= 1000
  • 0 <= len(agents) <= 1000
  • All task_id values in tasks are distinct integers, and all timestamps and durations are whole-hour integers.

Step-by-step walkthrough

  1. Understand the rules and pin down the interface

    schedule_tasks(tasks, max_concurrency, agents) receives the list of session dictionaries, the per-customer concurrency cap, and the list of available agent IDs. Each session has a fixed start_time and duration in hours: we cannot shift a session earlier or later, only decide which agent takes each session. Three rules make every boundary crystal-clear:

    • Half-open time intervals. A session with start_time = 2 and duration = 3 occupies hours 2, 3, and 4, written [2, 5) (meaning 2 is included and 5 is excluded). As soon as hour 5 begins, that session is over, so the same agent or customer can start another session at hour 5.
    • Linear hours (no midnight wrap-around). Because 0 <= start_time < 24 and 1 <= duration <= 24, a session starting at hour 23 for 3 hours occupies [23, 26). It does not wrap around to collide with [0, 2).
    • All-or-nothing output. Return {task_id: agent_id} covering every session if a valid assignment exists, or {} if any rule makes a full schedule impossible.
    Hour:       2     3     4     5     6     7     8
    Task 10:   [=================)                        occupies [2, 5)
    Task 20:               [===========)                  occupies [4, 6) -> overlaps Task 10 at hour 4
    Task 30:                     [=================)      occupies [5, 8) -> touches Task 10 at 5, no overlap
    
  2. Separate the two constraints: customer load vs. agent assignment

    At first glance, the customer concurrency limit and the agent limit look tangled together. Separating them makes the problem much simpler:

    1. Per-customer concurrency depends only on the input times. Because start times and durations are fixed, the number of sessions a customer has running during any hour is already fixed before we assign a single agent. If customer 500 has two overlapping sessions and max_concurrency = 1, no agent assignment can fix that. We can check this first as a clean yes/no test.
    2. Agent capacity is an interval partitioning problem. Once we know every customer obeys max_concurrency, customer IDs no longer matter. We only need to split the sessions across the available agents so no agent receives two overlapping sessions.

    Trying every agent for every call by brute force would explore A^n combinations for A agents and n calls. With n = 1000, even 2 agents gives 2^1000 possibilities, so we need a single forward sweep over time.

  3. Sort calls chronologically

    To simulate time moving forward from left to right, we first sort a copy of tasks by start_time. If we processed calls in arbitrary input order, we would make wrong decisions:

    Input order:  Task A [5, 6),  Task B [0, 2),  Task C [1, 7)    with 2 agents [1, 2]
    
    Unsorted mistake:
      - Task A [5, 6) takes agent 1 (agent 1 is now blocked at hour 5)
      - Task B [0, 2) takes agent 2
      - Task C [1, 7) overlaps Task A on agent 1 and Task B on agent 2 -> stuck!
    
    Sorted by start_time: Task B [0, 2), Task C [1, 7), Task A [5, 6)
      - Hour 0: Task B [0, 2) takes agent 1
      - Hour 1: Task C [1, 7) takes agent 2
      - Hour 5: Agent 1 finished at hour 2, so Task A [5, 6) reuses agent 1 -> success!
    

    We include task_id as a tie-breaker so Python never tries to compare two dict objects when two calls share the same start_time:

    def _sort_key(task: dict) -> tuple:
        # Sort primarily by start hour; break ties by task_id so dicts are never compared directly.
        return (task["start_time"], task["task_id"])
    
  4. Check per-customer concurrency with a min-heap

    As we scan calls in sorted start_time order, we want to know how many calls a customer still has running at the moment a new call starts.

    For each customer, we keep a min-heap (a binary tree stored in a list where index 0 is always the smallest value, allowing pushes and pops in logarithmic time) of the end_hour values of their currently active calls:

    1. Pop every end_hour <= start_hour from that customer's heap. Those calls have already ended.
    2. Every remaining entry in the heap started at or before start_hour (because we sorted by start_time) and ends strictly after start_hour. So len(customer_ends) is the exact number of calls that customer has running right now.
    3. If len(customer_ends) >= max_concurrency, adding the new call would exceed the limit, so we immediately return False (note this also catches max_concurrency <= 0 when len(customer_ends) is 0).

    Checking only at call start hours is enough because a customer's active call count only ever increases at the exact hour a new call starts.

    from typing import Dict, List
    import heapq
    
    
    def _customers_within_limit(ordered_tasks: List[dict], max_concurrency: int) -> bool:
        """Return True if no customer ever exceeds max_concurrency simultaneous calls."""
        # active_ends_by_customer: {customer_id: min-heap of end_hour ints for active calls}
        # Mini-shape example: {500: [5, 6], 600: [8]}
        active_ends_by_customer: Dict[int, List[int]] = {}
    
        for task in ordered_tasks:
            customer_id = task["customer_id"]
            start_hour = task["start_time"]
            end_hour = start_hour + task["duration"]
    
            customer_ends = active_ends_by_customer.setdefault(customer_id, [])
    
            # Use <= because intervals are half-open [start, end): a call ending at
            # start_hour has already hung up before this new call begins.
            while customer_ends and customer_ends[0] <= start_hour:
                heapq.heappop(customer_ends)
    
            # Every remaining entry started at or before start_hour and ends after start_hour.
            # Adding this call would push the customer to len(customer_ends) + 1 active calls.
            if len(customer_ends) >= max_concurrency:
                return False
    
            heapq.heappush(customer_ends, end_hour)
    
        return True
    
  5. Assign agents greedily using free and busy heaps

    Now we assign agents in chronological start_time order using a greedy algorithm (making a locally valid choice at each step without ever backtracking): whenever a call starts, hand it to any free agent.

    To find free agents quickly without scanning all agents each time, we maintain two min-heaps:

    • free_agents: idle agent_id values (deduplicated with set(agents) first so duplicate IDs in agents cannot double-book one person). Keeping free_agents as a heap simply picks the smallest idle ID first so outputs are predictable.
    • busy_agents: (end_hour, agent_id) pairs for agents currently on a call, ordered by end_hour so the soonest agent to finish sits at busy_agents[0].

    Why picking any free agent never paints us into a corner: All agents are interchangeable. Suppose a call starting at start_hour finds free_agents empty. That means every one of our A unique agents is currently inside busy_agents on a call that started <= start_hour and ends > start_hour. Together with the new call, A + 1 calls are all active during start_hour. By the pigeonhole principle, no algorithm could ever fit A + 1 simultaneous calls onto A agents. Therefore, our greedy sweep fails if and only if the input is genuinely impossible!

    def _assign_agents(ordered_tasks: List[dict], agents: List[int]) -> Dict[int, int]:
        """Greedily assign each call, in chronological start order, to any free agent."""
        # Deduplicate agent IDs so a repeated ID in the input list cannot be double-booked.
        # free_agents: min-heap of idle agent_id ints (e.g., [1, 2, 5]); smallest ID chosen first for determinism.
        free_agents = list(set(agents))
        heapq.heapify(free_agents)
    
        # busy_agents: min-heap of (end_hour, agent_id) tuples (e.g., [(2, 1), (5, 2)]),
        # keeping the soonest-finishing agent on top.
        busy_agents: List[tuple] = []
    
        # assignment: {task_id: agent_id} result mapping.
        assignment: Dict[int, int] = {}
    
        for task in ordered_tasks:
            task_id = task["task_id"]
            start_hour = task["start_time"]
            end_hour = start_hour + task["duration"]
    
            # Phase 1: Return every agent whose previous call ended by start_hour to the free pool.
            while busy_agents and busy_agents[0][0] <= start_hour:
                finished_end_hour, freed_agent = heapq.heappop(busy_agents)
                heapq.heappush(free_agents, freed_agent)
    
            # Phase 2: If no agent is free, all unique agents are busy across start_hour,
            # meaning (num_agents + 1) calls overlap right now and no valid schedule exists.
            if not free_agents:
                return {}
    
            # Phase 3: Book one free agent for [start_hour, end_hour).
            chosen_agent = heapq.heappop(free_agents)
            assignment[task_id] = chosen_agent
            heapq.heappush(busy_agents, (end_hour, chosen_agent))
    
        return assignment
    
  6. Trace a five-call example step by step

    Suppose max_concurrency = 1, agents = [10, 20, 30], and we have five calls:

    Hour:       0     1     2     3     4     5     6
    Task 1 (c1) [===========)                           [0, 2)
    Task 2 (c2)       [=================)               [1, 4)
    Task 3 (c1)             [=====)                     [2, 3)
    Task 4 (c3)             [=================)         [2, 5)
    Task 5 (c2)                         [===========)   [4, 6)
    
    1. Customer check: Customer 1 has [0, 2) and [2, 3) — at hour 2, end hour 2 is popped before [2, 3) is checked, so active count stays <= 1. Customer 2 has [1, 4) and [4, 6) — end hour 4 is popped at hour 4. Customer 3 has one call. _customers_within_limit returns True.
    2. Agent assignment with [10, 20, 30]:
    Call         start  Released from busy   free_agents   Chosen  busy_agents after
    -----------  -----  -------------------  ------------  ------  --------------------------
    (initial)    -      -                    [10, 20, 30]  -       []
    Task 1 [0,2) 0      none                 [10, 20, 30]  10      [(2, 10)]
    Task 2 [1,4) 1      none (2 > 1)         [20, 30]      20      [(2, 10), (4, 20)]
    Task 3 [2,3) 2      (2, 10)              [10, 30]      10      [(3, 10), (4, 20)]
    Task 4 [2,5) 2      none (3 > 2)         [30]          30      [(3, 10), (4, 20), (5, 30)]
    Task 5 [4,6) 4      (3, 10), (4, 20)     [10, 20]      10      [(5, 30), (6, 10)]
    

    The returned schedule is {1: 10, 2: 20, 3: 10, 4: 30, 5: 10}. Notice that if we only had two agents [10, 20], Task 4 at hour 2 would find free_agents = [] and return {} because Tasks 2, 3, and 4 all overlap during hour 2.

  7. Complete solution

    Put the pieces together inside schedule_tasks: sort a copy of the tasks once, verify customer concurrency, and run the greedy agent assignment.

    from typing import Dict, List
    import heapq
    
    
    def _sort_key(task: dict) -> tuple:
        # Sort primarily by start hour; break ties by task_id so dicts are never compared directly.
        return (task["start_time"], task["task_id"])
    
    
    def _customers_within_limit(ordered_tasks: List[dict], max_concurrency: int) -> bool:
        """Return True if no customer ever exceeds max_concurrency simultaneous calls."""
        # active_ends_by_customer: {customer_id: min-heap of end_hour ints for active calls}
        # Mini-shape example: {500: [5, 6], 600: [8]}
        active_ends_by_customer: Dict[int, List[int]] = {}
    
        for task in ordered_tasks:
            customer_id = task["customer_id"]
            start_hour = task["start_time"]
            end_hour = start_hour + task["duration"]
    
            customer_ends = active_ends_by_customer.setdefault(customer_id, [])
    
            # Use <= because intervals are half-open [start, end): a call ending at
            # start_hour has already hung up before this new call begins.
            while customer_ends and customer_ends[0] <= start_hour:
                heapq.heappop(customer_ends)
    
            # Every remaining entry started at or before start_hour and ends after start_hour.
            # Adding this call would push the customer to len(customer_ends) + 1 active calls.
            if len(customer_ends) >= max_concurrency:
                return False
    
            heapq.heappush(customer_ends, end_hour)
    
        return True
    
    
    def _assign_agents(ordered_tasks: List[dict], agents: List[int]) -> Dict[int, int]:
        """Greedily assign each call, in chronological start order, to any free agent."""
        # Deduplicate agent IDs so a repeated ID in the input list cannot be double-booked.
        # free_agents: min-heap of idle agent_id ints (e.g., [1, 2, 5]); smallest ID chosen first for determinism.
        free_agents = list(set(agents))
        heapq.heapify(free_agents)
    
        # busy_agents: min-heap of (end_hour, agent_id) tuples (e.g., [(2, 1), (5, 2)]),
        # keeping the soonest-finishing agent on top.
        busy_agents: List[tuple] = []
    
        # assignment: {task_id: agent_id} result mapping.
        assignment: Dict[int, int] = {}
    
        for task in ordered_tasks:
            task_id = task["task_id"]
            start_hour = task["start_time"]
            end_hour = start_hour + task["duration"]
    
            # Phase 1: Return every agent whose previous call ended by start_hour to the free pool.
            while busy_agents and busy_agents[0][0] <= start_hour:
                finished_end_hour, freed_agent = heapq.heappop(busy_agents)
                heapq.heappush(free_agents, freed_agent)
    
            # Phase 2: If no agent is free, all unique agents are busy across start_hour,
            # meaning (num_agents + 1) calls overlap right now and no valid schedule exists.
            if not free_agents:
                return {}
    
            # Phase 3: Book one free agent for [start_hour, end_hour).
            chosen_agent = heapq.heappop(free_agents)
            assignment[task_id] = chosen_agent
            heapq.heappush(busy_agents, (end_hour, chosen_agent))
    
        return assignment
    
    
    def schedule_tasks(tasks: List[dict], max_concurrency: int, agents: List[int]) -> Dict[int, int]:
        """Return {task_id: agent_id} for every task, or {} if no valid assignment exists."""
        # Process calls in non-decreasing start_time order without mutating the caller's list.
        ordered_tasks = sorted(tasks, key=_sort_key)
    
        # First verify per-customer concurrency, which depends only on call times, not agent choices.
        if not _customers_within_limit(ordered_tasks, max_concurrency):
            return {}
    
        # Then partition all calls across the available agents.
        return _assign_agents(ordered_tasks, agents)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine running the front desk of a call center with a wall clock ticking forward hour by hour. Because every call's start time and duration are fixed in advance, you can walk through the calls in chronological start order: first verify that no customer ever has too many simultaneous calls on the line, and then hand each starting call to whichever agent has already hung up from their previous call.

A naive approach tries every possible agent for each call by backtracking, which explores A^n combinations for A agents and n calls — completely impractical when n = 1000. Even scanning every agent's full calendar for each call wastes work when A is large. Instead, we use a min-heap (a priority-queue data structure that keeps the smallest element at index 0 and supports insertions and removals in logarithmic time) so we can instantly wake up agents whose previous call has ended.

Walk through Example 1 with max_concurrency = 2 and two agents [41, 42]: - Task 10 (customer 500, [2, 5)): starts at hour 2. Customer 500 has 0 active sessions (< 2). Agent 41 is free and takes Task 10 until hour 5. - Task 20 (customer 500, [4, 6)): starts at hour 4. Customer 500's [2, 5) session is still running (5 > 4), making 2 simultaneous sessions (<= 2). Agent 41 is busy until 5, so idle Agent 42 takes Task 20 until hour 6. - Task 30 (customer 600, [5, 8)): starts at hour 5. Customer 600 has 0 active sessions. Agent 41 finished Task 10 at hour 5 (5 <= 5), returns to the free pool, and takes Task 30, producing {10: 41, 20: 42, 30: 41}.

Complexity

  • Time: O(n log n + A + n log A) for n calls and A input agents. Sorting the n calls by start time takes O(n log n). In the customer check, each of the n calls is pushed onto and popped from its customer's min-heap at most once, costing at most O(log n) per operation (O(n log n) total). Deduplicating and heapifying the A agents takes O(A) linear time, and each of the n calls triggers at most one pop/push on busy_agents and one pop/push on free_agents, each costing O(log A) (O(n log A) total).
  • Space: O(n + A). The sorted task list, the per-customer heaps, and the output dictionary hold at most n entries each (O(n)), while free_agents and busy_agents together store at most A unique agents (O(A)).

Edge cases

  • Back-to-back calls ([0, 2) and [2, 3)): Intervals are half-open (including the start hour and excluding the end hour), so a call ending at hour 2 does not overlap a call starting at hour 2. Both can share one agent and count as 1 active call for the customer.
  • Duplicate IDs in agents (e.g., [7, 7]): Deduplicating with set(agents) ensures one physical agent is never double-booked onto two overlapping calls.
  • Zero agents (agents = []) or max_concurrency <= 0: With at least one task, no call can run, and the function returns {}.
  • Calls running past midnight (start_time = 23, duration = 3): Time moves linearly forward to [23, 26) without wrapping around to hour 0.
  • Multiple calls starting at the same hour: Breaking sort ties with task_id processes them deterministically one by one, and each sees the agents already booked by earlier calls at that hour.
  • Empty tasks list: Returns {} cleanly (though in a production API, returning an explicit boolean flag or raising an exception distinguishes "empty schedule" from "impossible schedule").

Common mistakes

  • Using < instead of <= when releasing finished calls. Writing busy_agents[0][0] < start_hour treats [0, 2) and [2, 3) as overlapping at hour 2, falsely rejecting valid back-to-back schedules.
  • Processing calls without sorting by start_time. Our heap sweep assumes time only moves forward. On unsorted input [5, 6), [0, 2), [1, 7) with two agents, booking [5, 6) on agent 1 and [0, 2) on agent 2 leaves neither agent free for the whole span [1, 7), even though [0, 2) and [5, 6) fit together on agent 1.
  • Only comparing a customer's call against their immediately previous call. When max_concurrency = 2, consider calls [0, 10), [1, 10), and [5, 6). Comparing [5, 6) only with [1, 10) sees just one overlap, missing that [0, 10) is also still active during hour 5 (3 simultaneous calls). A min-heap tracks all active calls accurately.
  • Sorting tasks in place with tasks.sort(). That mutates the caller's input list unexpectedly; sorted(tasks, ...) creates a safe copy.
  • Returning a partial dictionary on failure. When a later call cannot be placed, the specification requires returning {} rather than the assignments made so far.

Alternative approaches

  • Fixed 48-hour bucket arrays: Since 0 <= start_time < 24 and 1 <= duration <= 24, every call occupies hours inside [0, 47]. You can count active calls per customer using a 48-integer array per customer in O(48 * n) time. However, bucket counts only tell you whether enough agents exist; you still need the chronological sweep to output which agent takes each call.
  • Sweep-line events (+1 / -1): Turning each call [s, e) into an end event (e, -1) and a start event (s, +1) (sorting -1 before +1 at equal timestamps) computes peak concurrency in O(n log n) for arbitrary continuous timestamps.

Follow-up questions

  • How would your design change if each agent had a numeric proficiency tier and tasks specified a minimum required tier? The per-customer concurrency check stays identical, because customer load does not depend on agent tiers. However, chronological greedy assignment is no longer guaranteed to find a valid schedule when one exists, even with a best-fit heuristic (picking the lowest-tier free agent who meets the task's requirement): for agents A (tier 1) and B (tier 2), best-fit gives [0, 2) (needs 1) to A, is forced to give [1, 5) (needs 1) to B, and then fails on [3, 4) (needs 2), whereas giving [0, 2) to B and [1, 5) to A leaves B free for [3, 4). In production, keeping free agents sorted by tier for best-fit lookup in O(log A) time is a strong online heuristic, while offline exact scheduling can use integer linear programming (an optimization solver over binary decision variables) or backtracking for small batches.
  • How would you adapt the scheduler to handle live call overruns when an active conversation runs longer than planned? Model the live scheduler around an event loop driven by a time-ordered priority queue of call starts, planned ends, and overrun extensions. Keep each agent's future bookings in a sorted list so checking whether another agent has a free gap [s, e) takes O(log B) via binary search (repeatedly halving a sorted list to find the insertion point). When an active call runs past its planned end, find the bookings on that agent that now collide, reassign them to other agents who are free across their full intervals, re-verify the customer's concurrency limit against their next call, and fall back to an overflow queue or delay policy if every agent is full. Keeping a small buffer pool of unscheduled agents absorbs overruns gracefully.
  • How would you architect this service for millions of daily bookings and thousands of agents distributed across global time zones? Convert all call times and agent shift schedules into UTC (Coordinated Universal Time, a single global timeline immune to local daylight-saving jumps) using a standard time-zone database. Partition (shard, meaning split into independent horizontal slices) calls and agents by isolated skill/language pools so each pool runs its own scheduler without global lock contention — 1,000,000 calls per day is only about 12 calls per second overall (1,000,000 / 86,400). Store agent time-slot bookings in a database with a uniqueness constraint or conditional write on (agent_id, hour_slot) to prevent double-booking across replicas, and track per-customer concurrency in a shared low-latency store with atomic increments (indivisible counter updates) in case one customer places calls across multiple pools.

Follow-up questions

Similar questions

More Hippocratic Ai interview questions

All 1 Hippocratic Ai questions →