Task Assignment System with Expiration Windows
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests in-memory data modeling, time-based state management, priority queuing, and handling overlapping task assignments with TTL semantics.
Build an in-memory system that manages tasks and user assignments with time-to-live (TTL) behavior.
Core Entities
Task: identified by a unique id, has a name and a numeric priority.
User: identified by a unique id, has a quota limiting how many assignments can be simultaneously active.
Assignment: links a user to a task starting at startTime for a duration ttl. The assignment is considered active during the half-open interval [startTime, startTime + ttl) and becomes expired at startTime + ttl or later. An assignment can be marked completed, after which it no longer counts as active or expired.
Operations
Your implementation receives a sequence of operations and returns results for each.
Task Management
- createTask(task_id, name, priority): Create a new task. Return
Falseiftask_idalready exists, otherwiseTrue. - getTask(task_id): Return a dictionary
{"id": task_id, "name": name, "priority": priority}orNoneif the task does not exist. - updateTask(task_id, updates): Update fields in
updates(a dict with keys "name" and/or "priority"). ReturnFalseif the task does not exist, otherwiseTrue.
Querying Tasks
- topTasks(n): Return the top
ntasks by priority (higher priority first), breaking ties byidin ascending lexicographic order. Return a list of task dictionaries. - searchTasks(substring, n): Same as
topTasks, but only consider tasks whose name containssubstringas a substring.
User and Assignment Management
-
addUser(user_id, quota): Register a user with a maximum active assignment limit. Return
Falseifuser_idalready exists, otherwiseTrue. -
assignTask(user_id, task_id, start_time, ttl): Assign a task to a user starting at
start_timefor durationttl. The assignment fails (returnFalse) if:- The user or task does not exist
ttl <= 0- At time
start_time, the user already has a number of active assignments equal to or exceeding their quota
Otherwise, create the assignment and return
True. Multiple assignments of the same task to the same user are allowed and treated as distinct. -
activeTasks(user_id, time): Return a list of task IDs for all active assignments for this user at the given
time, sorted by(startTime, taskId)ascending. -
completeTask(user_id, task_id, time): Mark an assignment complete. Among all active assignments for this
(user_id, task_id)pair attime, complete the one with the earlieststartTime. ReturnTrueif an assignment was completed,Falseif no active assignment exists for this pair. -
expiredTasks(user_id, time): Return a list of task IDs for all expired (but not completed) assignments for this user at the given
time, sorted by(startTime, taskId)ascending.
Constraints
- All IDs are non-empty strings or integers
priorityis an integerquota >= 0n >= 0ttl,start_time, andtimeare non-negative integers- Time values are not necessarily monotonically increasing across operations
- At most 10⁴ operations
- At most 10³ tasks, 10³ users, and 10⁴ assignments total
Examples
Example 1
Input: task_assignment_system(['createTask', 'createTask', 'addUser', 'assignTask', 'activeTasks', 'completeTask', 'activeTasks', 'expiredTasks'], [[1, 'Write tests', 5], [2, 'Review code', 3], ['u1', 2], ['u1', 1, 10, 5], ['u1', 12], ['u1', 1, 14], ['u1', 14], ['u1', 15]])
Output: [True, True, True, True, [1], True, [], []]
Example 2
Input: task_assignment_system(['createTask', 'createTask', 'topTasks', 'searchTasks', 'updateTask', 'getTask'], [[2, 'Pay invoice', 4], [1, 'Invoice review', 4], [2], ['Invoice', 5], [2, {'priority': 7}], [2]])
Output: [True, True, [{'id': 1, 'name': 'Invoice review', 'priority': 4}, {'id': 2, 'name': 'Pay invoice', 'priority': 4}], [{'id': 1, 'name': 'Invoice review', 'priority': 4}], True, {'id': 2, 'name': 'Pay invoice', 'priority': 7}]
Hints
Hint 1
An assignment is active during [startTime, startTime + ttl) — note the half-open interval. Expiration begins exactly at startTime + ttl.
Hint 2
Track assignments per user to efficiently count active ones at a given timestamp and to locate candidates for completion.
Hint 3
Sorting tasks by priority is straightforward with a key function; avoid maintaining a persistent sorted structure unless queries dominate.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store tasks and users in dictionaries for constant-time lookup. Keep all assignments in a single list, with each assignment recording its user, task, start time, TTL, and completion status.
Task queries (topTasks, searchTasks): Sort the relevant tasks using a key that orders by descending priority, then ascending ID. Python's sort is stable and efficient for these sizes.
Assignment logic: When assigning a task at start_time, scan all assignments for that user and count how many are active at start_time (those where start <= start_time < start + ttl and not completed). If the count reaches the quota, reject the assignment.
Active and expired tasks: Filter assignments by user, completion status, and the appropriate time condition. The half-open interval [start, start + ttl) means an assignment is active when start <= time < start + ttl, and expired when time >= start + ttl.
Completion: Among active assignments for a given (user, task) pair, find the one with the smallest startTime and mark it completed. A completed assignment no longer appears in active or expired lists and no longer counts against the quota.
Why It Works
The half-open interval semantics ensure an assignment transitions cleanly from active to expired exactly at start + ttl, with no overlap. Completion prevents an assignment from ever being considered active or expired again, immediately freeing a quota slot. Filtering and sorting on demand keeps the logic simple and correct, at the cost of scanning the assignment list for each query.
Complexity
Let T be the number of tasks, U the number of users, and A the total assignments.
- createTask, getTask, updateTask, addUser: O(1)
- topTasks, searchTasks: O(T log T) for sorting, plus O(T) for substring filtering
- assignTask: O(A) to count active assignments for the user
- activeTasks, expiredTasks: O(A) to filter, plus O(A log A) to sort the result
- completeTask: O(A) to find matching active assignments
Space: O(T + U + A)
For small to medium problem sizes (up to 10⁴ operations and 10⁴ assignments), this straightforward approach is efficient and easy to verify.
from typing import List
def task_assignment_system(operations, arguments):
tasks = {}
users = {}
assignments = []
results = []
for operation, args in zip(operations, arguments):
if operation == "createTask":
task_id, name, priority = args
if task_id in tasks:
results.append(False)
else:
tasks[task_id] = {"id": task_id, "name": name, "priority": priority}
results.append(True)
elif operation == "getTask":
task = tasks.get(args[0])
results.append(dict(task) if task is not None else None)
elif operation == "updateTask":
task_id, updates = args
task = tasks.get(task_id)
if task is None:
results.append(False)
else:
if "name" in updates:
task["name"] = updates["name"]
if "priority" in updates:
task["priority"] = updates["priority"]
results.append(True)
elif operation == "topTasks":
n = args[0]
ordered = sorted(tasks.values(), key=lambda task: (-task["priority"], task["id"]))
results.append([dict(task) for task in ordered[:n]])
elif operation == "searchTasks":
substring, n = args
ordered = sorted(
(task for task in tasks.values() if substring in task["name"]),
key=lambda task: (-task["priority"], task["id"]),
)
results.append([dict(task) for task in ordered[:n]])
elif operation == "addUser":
user_id, quota = args
if user_id in users:
results.append(False)
else:
users[user_id] = quota
results.append(True)
elif operation == "assignTask":
user_id, task_id, start_time, ttl = args
if user_id not in users or task_id not in tasks or ttl <= 0:
results.append(False)
continue
active_count = sum(
assignment["userId"] == user_id
and assignment["startTime"] <= start_time < assignment["startTime"] + assignment["ttl"]
for assignment in assignments
)
if active_count >= users[user_id]:
results.append(False)
else:
assignments.append({
"userId": user_id,
"taskId": task_id,
"startTime": start_time,
"ttl": ttl,
"completed": False,
})
results.append(True)
elif operation == "activeTasks":
user_id, time = args
active = [
assignment for assignment in assignments
if assignment["userId"] == user_id
and not assignment["completed"]
and assignment["startTime"] <= time < assignment["startTime"] + assignment["ttl"]
]
active.sort(key=lambda assignment: (assignment["startTime"], assignment["taskId"]))
results.append([assignment["taskId"] for assignment in active])
elif operation == "completeTask":
user_id, task_id, time = args
matching = [
assignment for assignment in assignments
if assignment["userId"] == user_id
and assignment["taskId"] == task_id
and not assignment["completed"]
and assignment["startTime"] <= time < assignment["startTime"] + assignment["ttl"]
]
if not matching:
results.append(False)
else:
earliest = min(matching, key=lambda assignment: assignment["startTime"])
earliest["completed"] = True
results.append(True)
elif operation == "expiredTasks":
user_id, time = args
expired = [
assignment for assignment in assignments
if assignment["userId"] == user_id
and not assignment["completed"]
and assignment["startTime"] + assignment["ttl"] <= time
]
expired.sort(key=lambda assignment: (assignment["startTime"], assignment["taskId"]))
results.append([assignment["taskId"] for assignment in expired])
else:
results.append(None)
return results