Assign Support Tickets to Agents Within Concurrency Limits
Greedy & IntervalsModel answerLast updated
Given a list of fixed-time support tickets, assign each to an agent while respecting per-client concurrency caps and an optional agent pool size.
Background
You are building the assignment engine for a support ticketing platform. Incoming tickets arrive with a fixed start time and a known handling duration. Your job is to map every ticket to a support agent so the platform can route work without conflicts.
Task
Implement the function:
def assign_tickets(tickets, max_concurrency, num_agents=None):
...
It should return a dictionary mapping each ticket_id to an agent_id (agents are numbered from 0). If it is impossible to satisfy all constraints, return an empty dictionary {}.
Inputs
tickets: a list of dictionaries, each with:ticket_id(int) — unique identifier for the ticketclient_id(int) — the client who opened the ticketstart_time(int) — the hour at which handling beginsduration(int) — how many hours the ticket takes to resolve
max_concurrency(int) — the maximum number of tickets a single client may have in-flight at the same timenum_agents(int orNone) — if given, the total number of available agents; ifNone, treat the pool as unbounded and use as few agents as possible
Rules
- An agent can handle at most one ticket at a time.
- A ticket must be assigned to an agent who is free for its entire duration.
- Intervals are half-open: a ticket covering
[start, start + duration)ends beforestart + duration, so an agent finishing at hour4is free to take a ticket starting at hour4. - Start times are fixed — you are assigning tickets to agents, not rescheduling them.
- No client may have more than
max_concurrencytickets active at the same instant.
Example
tickets = [
{'ticket_id': 1, 'client_id': 42, 'start_time': 0, 'duration': 3},
{'ticket_id': 2, 'client_id': 42, 'start_time': 2, 'duration': 2},
]
assign_tickets(tickets, max_concurrency=1)
# Tickets [0,3) and [2,4) overlap for client 42 → impossible
# returns {}
assign_tickets(tickets, max_concurrency=2)
# returns {1: 0, 2: 1} (or any valid two-agent assignment)
Constraints
0 <= start_time < 241 <= duration <= 241 <= len(tickets) <= 1000- All
ticket_idvalues are unique - Time is measured in integer hourly blocks; no day wrap-around
Hints
Hint 1
Before touching agent assignment at all, check whether the client concurrency rule is even satisfiable. Because start times are fixed, this is a pure feasibility question you can answer with a sweep line over each client's intervals independently — no assignment decisions needed.
Hint 2
For the agent assignment itself, think of it as interval partitioning: sort tickets by start time, maintain a min-heap of (end_time, agent_id) for busy agents, and reclaim any agent whose end_time is ≤ the current ticket's start_time. The half-open rule means 'end ≤ start' is the right release condition, not 'end < start'.
Hint 3
To prove your greedy uses the fewest agents possible, ask: when does it open a new agent? Only when every existing agent is still busy. Count how many tickets overlap at that moment — that count is a lower bound on the number of agents any valid solution needs, so the greedy is optimal.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem looks like one big scheduling puzzle, but it actually splits cleanly into two independent subproblems.
Why the split works: start times are fixed. You cannot move a ticket to resolve a conflict — you can only choose which agent takes it. That means the client concurrency constraint is either satisfiable or it isn't, regardless of how you assign agents. Check it first. If it passes, agent assignment is a classic interval partitioning problem.
Step 1 — Client feasibility via sweep line
For each client, collect two events per ticket: (start, +1) and (end, -1) where end = start + duration. Sort the events. At equal timestamps, sort ends before starts (-1 before +1) to implement the half-open rule — a ticket ending at hour 3 does not count as concurrent with one starting at hour 3.
Scan the sorted events keeping a running count of active tickets. If it ever exceeds max_concurrency, return {} immediately. No agent assignment can fix this.
Step 2 — Greedy interval partitioning for agents
Sort all tickets by (start_time, ticket_id). Process them in order, maintaining two min-heaps:
busy:(end_time, agent_id)— agents currently handling a ticketfree:agent_id— agents with nothing to do
For each ticket starting at time s:
- Pop every entry from
busywhoseend_time <= sand push those agent ids intofree. This is the half-open release condition. - If
freeis non-empty, pull the smallest agent id from it. Otherwise, open a new agent. If that would exceednum_agents, return{}. - Record the assignment and push
(end_time, agent_id)ontobusy.
Why this is optimal (minimum agents): the greedy opens a new agent only when all existing agents are busy at time s. If k agents are all busy, there are at least k tickets whose intervals all contain s — meaning k is a lower bound. Since the greedy never opens more agents than that lower bound demands, it uses exactly the minimum. Consequently, if it fails against a fixed num_agents, no valid assignment exists.
Complexity
| Phase | Time | Space |
|---|---|---|
| Sweep line (2n events per client, total 2n) | O(n log n) | O(n) |
| Sort tickets | O(n log n) | O(n) |
| Heap operations | O(n log n) | O(n) |
Overall: O(n log n) time, O(n) space.
Edge cases to call out
- Back-to-back tickets (end == start): allowed — the half-open rule handles this automatically with the
<= srelease condition. max_concurrency = 0with any ticket: immediately infeasible, returns{}.- Ticket ending past hour 24: handled correctly since no wrap-around is assumed.
- Many tickets sharing the same start time: each needs a distinct agent; ties broken by
ticket_idfor deterministic output. num_agentssmaller than peak overlap depth: returns{}correctly.- Duplicate
ticket_ids: invalid input — worth mentioning you'd validate this at the API boundary in production.
Python solution
import heapq
from collections import defaultdict
def assign_tickets(tickets, max_concurrency, num_agents=None):
"""
Assign each ticket to an agent (0-indexed) such that:
- no agent handles two overlapping tickets
- no client exceeds max_concurrency simultaneous tickets
Intervals are half-open: [start, start + duration).
Returns {} if a valid assignment is impossible.
"""
if not tickets:
return {}
# --- Phase 1: client concurrency feasibility ---
client_events = defaultdict(list)
for t in tickets:
s = t['start_time']
e = s + t['duration']
client_events[t['client_id']].append((s, 1)) # start
client_events[t['client_id']].append((e, -1)) # end
for evs in client_events.values():
evs.sort() # equal times: -1 (end) sorts before +1 (start)
active = 0
for _, delta in evs:
active += delta
if active > max_concurrency:
return {}
# --- Phase 2: greedy interval partitioning ---
ordered = sorted(tickets, key=lambda t: (t['start_time'], t['ticket_id']))
busy = [] # min-heap: (end_time, agent_id)
free = [] # min-heap: agent_id
next_agent = 0
assignment = {}
for t in ordered:
s = t['start_time']
e = s + t['duration']
# Reclaim agents whose tickets have ended by time s (half-open: <= s)
while busy and busy[0][0] <= s:
_, agent = heapq.heappop(busy)
heapq.heappush(free, agent)
if free:
agent = heapq.heappop(free)
else:
if num_agents is not None and next_agent >= num_agents:
return {}
agent = next_agent
next_agent += 1
assignment[t['ticket_id']] = agent
heapq.heappush(busy, (e, agent))
return assignment
Tracing the example:
With max_concurrency=1, client 42 has events (0,+1),(2,+1),(3,-1),(4,-1). After the first two events the active count hits 2, which exceeds the limit, so the function returns {}.
With max_concurrency=2, the check passes. Tickets sorted by start: ticket 1 at t=0, ticket 2 at t=2. Ticket 1 gets agent 0 (new). At t=2, agent 0's end is 3, which is not <= 2, so it stays busy — ticket 2 gets agent 1 (new). Result: {1: 0, 2: 1}.
Common mistakes
- Using
< sinstead of<= sfor the release condition — this incorrectly blocks back-to-back assignments. - Running the client feasibility check and agent assignment as one pass — they're independent and mixing them complicates both.
- Forgetting that the greedy can fail against a fixed pool, and not returning
{}in that case. - Sorting events without a secondary key, causing ends and starts at the same hour to be processed in arbitrary order.
Follow-up directions
Skill matching: if agents have skill levels and tickets require a minimum skill, a straight greedy no longer works — a low-skill ticket can block a high-skill agent. This pushes toward a bipartite matching or priority-based greedy with constraints.
Soft client concurrency: if exceeding max_concurrency incurs a penalty rather than being a hard block, the problem becomes a cost-minimization variant, solvable with weighted interval scheduling or flow-based approaches.
Dynamic arrivals: if tickets arrive in real time with unknown future demand, you need an online algorithm, which changes both the data structure and the optimality guarantees.