Work Queue Tracker with Owners, Closing, and Late Lookups
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a task tracker driven by a list of operations, handling creation, reassignment, completion, and multi-key sorted queries while returning one result per operation.
Work Queue Tracker
You are building the logic of a small in-memory work tracker. Rather than writing a class, you implement one function that receives a whole script of operations and returns what each operation produced.
Task records
Every task has:
- an id (string), unique across the tracker,
- a description (string),
- a priority (integer, larger means more important),
- a deadline (integer timestamp),
- a state, which is either
"PENDING"or"COMPLETED", - an owner: a user id, or
Nonewhen nobody holds it.
Input
operations: a list of operation names.arguments: a list of the same length, wherearguments[i]is the argument list foroperations[i].
Process the operations in order, starting from an empty tracker.
Operations
| Operation | Arguments | Result |
|---|---|---|
"create_task" | [task_id, description, priority, deadline] | True if a new task was added; False if a task with that id already exists (even a completed one). |
"assign_task" | [task_id, user_id] | True if the task exists and is "PENDING", in which case its owner becomes user_id (replacing any previous owner). False if the task does not exist or is completed; nothing changes then. |
"complete_task" | [task_id] | True if the task exists and is "PENDING", in which case it becomes "COMPLETED". False otherwise. |
"get_user_tasks" | [user_id, sort_by] | A list of ids of tasks that are "PENDING" and owned by user_id, ordered as described below. An empty list if there are none. |
"get_overdue_tasks" | [current_time] | A list of ids of "PENDING" tasks with deadline < current_time (strictly less), whether or not they have an owner. Sorted by deadline ascending, ties by id ascending. |
New tasks start as "PENDING" with no owner.
Ordering for get_user_tasks
sort_by == "priority": priority descending, then deadline ascending, then id ascending.sort_by == "deadline": deadline ascending, then priority descending, then id ascending.
Ids are compared as ordinary strings.
Output
Return a list with one entry per operation, in the same order as the input: a boolean for create_task, assign_task, complete_task, and a list of ids for the two query operations. Any operation name not listed above produces no entry in the output.
Constraints
1 <= len(task_id), len(user_id) <= 32, alphanumeric.1 <= priority <= 10^51 <= deadline, current_time <= 2 * 10^9- At most
20,000operations in total. sort_byis always"priority"or"deadline".
Examples
Example 1
Input: run_task_tracker(['create_task', 'create_task', 'create_task', 'assign_task', 'assign_task', 'assign_task', 'get_user_tasks', 'complete_task', 'get_user_tasks', 'get_overdue_tasks'], [['T1', 'Audit logs', 2, 100], ['T2', 'Fix bug', 5, 50], ['T3', 'Deploy', 2, 80], ['T1', 'alice'], ['T2', 'alice'], ['T3', 'alice'], ['alice', 'priority'], ['T2'], ['alice', 'priority'], [90]])
Output: [True, True, True, True, True, True, ['T2', 'T3', 'T1'], True, ['T3', 'T1'], ['T3']]
Hints
Hint 1
Keep one dictionary from task id to a record holding priority, deadline, state, and owner; every boolean operation is a lookup plus a state check.
Hint 2
Both the priority-first and deadline-first orderings can be expressed as a single tuple sort key by negating the priority so it sorts descending while the other fields stay ascending.
Hint 3
A completed task must be excluded from both queries, and a task that was reassigned must only show up for its latest owner. Filtering by state and current owner at query time handles this naturally.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary mapping each task id to a record with its priority, deadline, state, and owner. Walk through the operations in order and handle each one against this dictionary.
- create_task: if the id is already a key, return
Falseand leave the existing record alone. Otherwise insert a"PENDING", unowned record and returnTrue. - assign_task: look up the task. If it is missing or not pending, return
False. Otherwise overwrite its owner and returnTrue. Reassignment is simply an overwrite. - complete_task: same existence and pending check, then flip the state to
"COMPLETED". - get_user_tasks: collect the tasks that are pending and whose current owner equals the user, then sort with a tuple key. Negating priority makes it sort descending while the remaining fields stay ascending:
"priority":(-priority, deadline, task_id)"deadline":(deadline, -priority, task_id)
- get_overdue_tasks: collect pending tasks with
deadline < current_time(strict) and sort by(deadline, task_id).
Unknown operation names are skipped and add nothing to the output.
Why it is correct
- The only state change is
PENDING -> COMPLETED, and it happens at most once. Bothassign_taskandcomplete_taskrefuse non-pending tasks, so completed tasks never change owner and cannot be completed twice. - The owner is stored on the record itself, so a reassigned task is reported only for its latest owner. There is no second structure that could go out of sync.
- Task ids are unique, so including the id as the last element of each sort key gives a total order, and the output is fully determined.
- A task whose deadline equals the current time is not overdue because the comparison is strict.
- Unowned pending tasks are still returned by the overdue query because it scans all tasks rather than only owned ones.
Complexity
Let N be the number of tasks.
create_task,assign_task,complete_task: O(1) average.get_user_tasks: O(N + k log k) with the simple scan, wherekis the number of matches.get_overdue_tasks: O(N + m log m), wheremis the number of overdue tasks.- Space: O(N).
With at most 20,000 operations, the linear scans per query are acceptable. A per-user index of pending ids would reduce get_user_tasks to O(k log k) if needed, as long as it is updated on reassignment and completion.
Reference solution
from typing import List
def run_task_tracker(operations: List[str], arguments: List[List]) -> List:
tasks = {}
results = []
for operation, args in zip(operations, arguments):
if operation == "create_task":
task_id, description, priority, deadline = args
if task_id in tasks:
results.append(False)
else:
tasks[task_id] = {
"description": description,
"priority": priority,
"deadline": deadline,
"status": "PENDING",
"assignee": None,
}
results.append(True)
elif operation == "assign_task":
task_id, user_id = args
task = tasks.get(task_id)
if task is None or task["status"] != "PENDING":
results.append(False)
else:
task["assignee"] = user_id
results.append(True)
elif operation == "complete_task":
task = tasks.get(args[0])
if task is None or task["status"] != "PENDING":
results.append(False)
else:
task["status"] = "COMPLETED"
results.append(True)
elif operation == "get_user_tasks":
user_id, sort_by = args
matching = [
(tid, t) for tid, t in tasks.items()
if t["status"] == "PENDING" and t["assignee"] == user_id
]
if sort_by == "priority":
matching.sort(key=lambda it: (-it[1]["priority"], it[1]["deadline"], it[0]))
else:
matching.sort(key=lambda it: (it[1]["deadline"], -it[1]["priority"], it[0]))
results.append([tid for tid, _ in matching])
elif operation == "get_overdue_tasks":
current_time = args[0]
matching = [
(tid, t) for tid, t in tasks.items()
if t["status"] == "PENDING" and t["deadline"] < current_time
]
matching.sort(key=lambda it: (it[1]["deadline"], it[0]))
results.append([tid for tid, _ in matching])
return results