Roster Coverage and Rating Leaderboard Simulator
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a command log against a stateful tracker that merges per-agent time intervals and ranks agents by average rating with alphabetical tie-breaking.
Roster Coverage and Rating Leaderboard
A support team keeps a small in-memory tracker for its agents. It records the time ranges each agent worked and the satisfaction scores customers gave them. You will implement the tracker and a driver function that replays a log of commands against it.
The tracker
Create a class AgentTracker. Its method names must match the command names below exactly, because the driver looks them up by name.
add_shift(agent_id, start, end)records that the agent worked during the closed range[start, end]. Ranges can overlap and can arrive in any order. It returnsNone.get_merged_shifts(agent_id)returns the agent's total coverage as a list of[start, end]pairs.- The pairs must be pairwise disjoint and sorted by start in ascending order.
- Ranges that overlap or merely touch at an endpoint must be combined. For example,
[1, 3]and[3, 5]become[1, 5]. - An agent with no recorded shifts yields
[].
record_rating(agent_id, score)stores one integer rating for the agent. It returnsNone.get_top_agents(k)returns up tok(agent_id, average_rating)pairs.- The average is the sum of the agent's ratings divided by the number of ratings, as a float.
- Order by average descending. If two averages are equal, order by
agent_idascending in lexicographic order. - Agents with no ratings are never included.
- If fewer than
kagents have ratings, return all of them. If there are none, or ifk <= 0, return[].
The driver function
Implement the function whose signature is given in the starter code. It takes:
operations: a list of command names, each one of the four method names above.arguments: a list of the same length.arguments[i]is the list of positional arguments foroperations[i].
The function creates one fresh AgentTracker, executes the commands in order, and returns a list of the same length. Entry i is the value returned by command i, so commands that return nothing contribute None.
Constraints
operationsandargumentshave the same length, at most20,000.agent_idis a string.startandendare integers withstart <= end. Ratings are integers.get_merged_shiftsmust not expose internal state: modifying a returned list must not affect the tracker.- Equal averages must be treated as ties even if they come from different counts (for example
8/2and4/1).
Examples
Example 1
Input: replay_agent_log(['add_shift', 'add_shift', 'add_shift', 'get_merged_shifts', 'record_rating', 'record_rating', 'record_rating', 'record_rating', 'get_top_agents'], [['alice', 9, 12], ['alice', 11, 14], ['alice', 16, 18], ['alice'], ['alice', 5], ['alice', 3], ['bob', 4], ['charlie', 5], [2]])
Output: [None, None, None, [[9, 14], [16, 18]], None, None, None, None, [['charlie', 5], ['alice', 4]]]
Hints
Hint 1
Treat shifts and ratings as two independent pieces of state, each in a dictionary keyed by agent id.
Hint 2
For shifts, either store raw ranges and sort and sweep them on query, or keep each agent's list sorted and disjoint and fold in every new range. Use `<=` when comparing a start to the current end so touching ranges merge.
Hint 3
For ratings, keep only a running total and a count per agent. To rank, sort with the key `(-average, agent_id)` and slice the first `max(0, k)` entries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The tracker has two independent halves, and each gets its own state.
Shifts. For each agent, keep a list of [start, end] ranges that is always sorted by start and pairwise disjoint (no overlaps, no touching). To insert a new range:
- Binary search for the first stored range whose start is at or after the new
start. - If the range just before that position ends at or after
start, it overlaps or touches the new one, so step back one position to include it. - Scan forward while the next stored range starts at or before the current merged end. Absorb each one by taking the minimum start and maximum end.
- Replace the absorbed slice with the single merged range.
Reading is then just a copy of the list. Copying each pair stops callers from mutating internal state.
Ratings. For each agent, store a running total and a count, so recording a rating is O(1). To rank, build (agent_id, total / count) for every rated agent, sort with the key (-average, agent_id), and return the first max(0, k) entries. Only agents with a count are included, so unrated agents never appear.
Driver. Create one tracker, look up each method by name with getattr, call it with the unpacked arguments, and collect the return values. Void methods yield None.
Why it is correct
The invariant is that each agent's list is sorted and disjoint with gaps between ranges. Every range before position i - 1 ends strictly before start, so it cannot interact with the new range. The forward scan absorbs exactly the ranges whose start is at most the growing merged end. The first range it skips starts strictly after the merged end, and so does everything after it. The merged range therefore sits between its neighbours with gaps on both sides, and the invariant holds after every insertion. The inclusive comparisons make touching ranges merge.
For ratings, total / count is the average by definition, and the key (-average, agent_id) gives descending average and then ascending id. Equal rational averages such as 8/2 and 4/1 give identical floats because IEEE division is correctly rounded, so ties are detected properly.
Complexity
Let m be the number of stored ranges for one agent and n the number of rated agents.
add_shift: O(log m) for the search plus O(m) worst case for the list slice replacement. The merge scan is amortized, since each range is absorbed at most once.get_merged_shifts: O(m).record_rating: O(1).get_top_agents: O(n log n).
Space is O(total stored ranges + n). With at most 20,000 commands, this is comfortably fast.
Reference solution
from bisect import bisect_left
from typing import List
class AgentTracker:
def __init__(self):
self.shifts = {}
self.rating_totals = {}
self.rating_counts = {}
def add_shift(self, agent_id, start, end):
intervals = self.shifts.setdefault(agent_id, [])
i = bisect_left(intervals, [start, start])
if i > 0 and intervals[i - 1][1] >= start:
i -= 1
merged_start, merged_end = start, end
j = i
while j < len(intervals) and intervals[j][0] <= merged_end:
merged_start = min(merged_start, intervals[j][0])
merged_end = max(merged_end, intervals[j][1])
j += 1
intervals[i:j] = [[merged_start, merged_end]]
def get_merged_shifts(self, agent_id):
return [interval[:] for interval in self.shifts.get(agent_id, [])]
def record_rating(self, agent_id, score):
self.rating_totals[agent_id] = self.rating_totals.get(agent_id, 0) + score
self.rating_counts[agent_id] = self.rating_counts.get(agent_id, 0) + 1
def get_top_agents(self, k):
ranked = [
(agent_id, self.rating_totals[agent_id] / count)
for agent_id, count in self.rating_counts.items()
]
ranked.sort(key=lambda item: (-item[1], item[0]))
return ranked[:max(0, k)]
def replay_agent_log(operations: List[str], arguments: List[List]) -> List:
tracker = AgentTracker()
results = []
for operation, args in zip(operations, arguments):
results.append(getattr(tracker, operation)(*args))
return results