Build a Layered In-Memory Work Tracker with Quotas and Deadlines
Data Structure DesignModel answerLast updated
Design an in-memory work tracker in four growing stages: CRUD, name and priority queries, per-user limits with timed assignments, then completion and lateness reports.
Build a Layered In-Memory Work Tracker
You are asked to implement an in-memory work tracker as a class. The work is split into four stages. Each stage builds on the one before it, and everything written for earlier stages must keep working unchanged when later stages are added.
No exact method names or return formats are prescribed. Define a small, clean interface yourself, and state explicitly the rule you pick for every point left open (ID format, timestamps, missing items, ties, boundaries). Keep each such rule in one place in the code so it is easy to change.
Stage 1: create, modify and fetch
Support three operations on work items: create one, modify one, and fetch one.
Decide and state:
- Which fields an item has (for instance a name and a numeric priority), and whether two items may share a name.
- Whether IDs are generated by the system or supplied by the caller.
- Whether a modification overwrites all fields or only those provided.
- What is returned when the item does not exist or the input is invalid.
Stage 2: name lookup and priority listing
Add two read operations: finding items by name, and listing items ordered by priority.
Decide and state:
- Whether name lookup is exact, prefix or substring, and whether it is case sensitive.
- The order in which lookup results come back.
- Whether a larger priority means more important, the sort direction, and the tie-breaker that makes the order fully deterministic.
- Whether listing can be capped to the top N.
Stage 3: users, limits and expiring assignments
Add users, each with a quota, plus time-based assignments of items to users. An assignment has a start time and automatically stops being active after a given duration.
Decide and state:
- Whether the quota caps simultaneously active assignments or the lifetime total.
- Whether an expired assignment immediately frees quota.
- Whether an item may be assigned to several users at once, and whether it may be re-assigned to the same user after expiry.
- Whether an assignment ending exactly at the query timestamp is still active.
- Whether every call carries a timestamp, and whether timestamps never decrease.
Stage 4: finishing work and lateness reporting
Add the ability for a user to mark an assigned item as finished, and a report of late assignments.
Decide and state:
- Whether an assignment is late when it expired without being finished, and whether finishing after expiry is allowed.
- Whether finishing releases the user's quota.
- Whether the report covers one user or everyone, and its ordering.
- What happens when someone tries to finish an item that is not actively assigned to them.
What is expected
Describe your design (data structures and the status model for assignments), give the complexity of each operation, and provide working code for all four stages. Call out the trade-offs you made, especially between simple scans and maintained indexes.
Hints
Hint 1
Start with a dictionary from item ID to a small record object. Give the record only the fields you need now, and keep the class layout so extra fields and maps can be added later without touching Stage 1 code.
Hint 2
Make every ordering a full sort key, for example (-priority, name, id). With a unique final component there is never any ambiguity, which makes the results repeatable and easy to test.
Hint 3
Model each assignment with an explicit status (active, finished, expired) and compute expiry lazily from the current timestamp rather than running a background timer. Put the 'is active at time t' test in one helper so the boundary rule lives in a single place.
Hint 4
For quotas, count only assignments that the chosen rule says consume quota, evaluated at the call's timestamp. Keep a per-user list of assignments so that count is cheap.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is to keep one authoritative record per concept, derive everything else from it, and evaluate time lazily. Below, the rules I chose are stated up front; each is implemented in exactly one helper.
Rules chosen
- IDs are generated by the system as
"t1","t2", ... using a counter. - Every time-sensitive call receives an integer timestamp
now, assumed non-decreasing. - Missing item, missing user or invalid input returns
NoneorFalse, never an exception. - Higher priority means more important. Listing order is priority descending, then name ascending, then ID ascending.
- Name search is exact and case sensitive; results are ordered by ID creation order.
- Quota limits simultaneously active assignments. Finishing or expiring frees quota.
- An assignment covers the half-open interval
[start, start + duration), so at exactlystart + durationit is already expired. - An item can have at most one active assignment at a time, but may be reassigned after expiry or completion.
- An assignment is overdue if it has expired without being finished. Finishing after expiry is rejected.
- The overdue report covers all users, ordered by (expiry time, item ID).
Data model
tasks: dict[id -> Task(name, priority, seq)]by_name: dict[name -> list[id]](optional index for Stage 2)users: dict[user -> quota]assignments: list[Assignment(task, user, start, end, finished)], plusactive_by_task: dict[task -> Assignment]andby_user: dict[user -> list[Assignment]].
Assignment status is derived, not stored: finished if the flag is set, active if now < end and not finished, otherwise overdue (expired and unfinished).
Code
class Task:
def __init__(self, tid, name, priority, seq):
self.id, self.name, self.priority, self.seq = tid, name, priority, seq
class Assignment:
def __init__(self, task, user, start, end):
self.task, self.user, self.start, self.end = task, user, start, end
self.finished = False
def is_active(self, now): # the only place the boundary rule lives
return not self.finished and self.start <= now < self.end
def is_overdue(self, now):
return not self.finished and now >= self.end
class WorkTracker:
def __init__(self):
self.tasks, self.by_name = {}, {}
self.users, self.by_user, self.active_by_task = {}, {}, {}
self.counter = 0
# Stage 1
def add(self, name, priority):
if not name or not isinstance(priority, int):
return None
self.counter += 1
tid = f"t{self.counter}"
self.tasks[tid] = Task(tid, name, priority, self.counter)
self.by_name.setdefault(name, []).append(tid)
return tid
def update(self, tid, name=None, priority=None):
t = self.tasks.get(tid)
if t is None:
return False
if name is not None and name != t.name:
self.by_name[t.name].remove(tid)
t.name = name
self.by_name.setdefault(name, []).append(tid)
if priority is not None:
t.priority = priority
return True
def get(self, tid):
t = self.tasks.get(tid)
return None if t is None else (t.id, t.name, t.priority)
# Stage 2
def find_by_name(self, name):
return sorted(self.by_name.get(name, []), key=lambda i: self.tasks[i].seq)
def list_by_priority(self, limit=None):
ordered = sorted(self.tasks.values(),
key=lambda t: (-t.priority, t.name, t.seq))
ids = [t.id for t in ordered]
return ids if limit is None else ids[:limit]
# Stage 3
def add_user(self, user, quota):
if user in self.users or quota < 0:
return False
self.users[user] = quota
self.by_user[user] = []
return True
def assign(self, tid, user, now, duration):
if tid not in self.tasks or user not in self.users or duration <= 0:
return False
cur = self.active_by_task.get(tid)
if cur and cur.is_active(now):
return False
used = sum(a.is_active(now) for a in self.by_user[user])
if used >= self.users[user]:
return False
a = Assignment(tid, user, now, now + duration)
self.by_user[user].append(a)
self.active_by_task[tid] = a
return True
# Stage 4
def complete(self, tid, user, now):
a = self.active_by_task.get(tid)
if a is None or a.user != user or not a.is_active(now):
return False
a.finished = True
return True
def overdue(self, now):
late = [a for lst in self.by_user.values() for a in lst
if a.is_overdue(now)]
late.sort(key=lambda a: (a.end, a.task))
return [(a.task, a.user, a.end) for a in late]
Complexity
add,get,update: O(1) average.find_by_name: O(k log k) for k matches.list_by_priority: O(n log n); a scan plus sort is fine at assessment scale. A sorted container or a heap for top-N (O(n log N)) is an upgrade if listings are frequent.assign: O(a) for the user's assignment count; can become O(1) by keeping an active counter and a min-heap of expiry times that is drained lazily before each check.complete: O(1).overdue: O(A log A) over all assignments.
Trade-offs
- Lazy expiry avoids timers and keeps behaviour deterministic given the timestamps.
- A name index costs a little bookkeeping on update but speeds lookup; a plain scan is also acceptable for small inputs.
- Putting all boundary logic in
is_activeandis_overduemakes a changed rule a one-line fix.
Common mistakes
- Treating the expiry instant as still active, causing off-by-one errors at the boundary.
- Counting expired or finished assignments against quota.
- Sorting without a unique final tie-breaker, producing unstable output.
- Forgetting to update the name index when a task is renamed.
- Rewriting earlier-stage structures instead of extending them, which breaks previously passing behaviour.
- Letting a user finish an item assigned to someone else, or one whose assignment already expired.
Likely follow-ups
Allowing multiple concurrent assignees per item, unassigning early, extending an assignment, supporting substring or prefix search with a trie, and persisting state across restarts.