Simulate a Task Management Engine with CRUD Operations
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate an in-memory task tracker handling creation, retrieval, updates, filtering, and deletion of tasks with valid state validation.
Design an in-memory task manager that processes a sequence of standard CRUD operations on tasks. Each task is represented by a dictionary containing three keys:
"id": a unique positive integer identifier."title": a string specifying the task title."status": a string indicating the current status, which must be one of"new","pending", or"resolved".
The engine starts empty. Task identifiers are assigned sequentially starting from 1 (i.e., 1, 2, 3, ...) and incremented every time a new task is created. IDs are never reused, even if tasks are deleted.
You are given a list of command strings operations and a corresponding list of argument lists arguments. Process each operation in order and record its output in a returned list.
Supported Operations
-
create:args = [title]- Creates a new task with the given
titleand default status"new". - Assigns the next available auto-incremented ID.
- Appends a copy of the created task object to the results list.
- Creates a new task with the given
-
get:args = [task_id]- Retrieves the task dictionary corresponding to
task_id. - Appends a copy of the task object if found, or
Noneif no task exists with that ID.
- Retrieves the task dictionary corresponding to
-
list:args = []orargs = [status_filter]- If
argsis empty orargs[0]isNone, retrieves all currently existing tasks. - If
args[0]is a string status, retrieves all existing tasks matching that status. - If
args[0]is a non-Nonestring that is not one of"new","pending", or"resolved", raises aValueError. - Appends a list of copies of all matching task dictionaries to the results list, ordered by task ID ascending.
- If
-
update:args = [task_id, new_title, new_status]- Finds the task with ID
task_id. If the task does not exist, appendsNoneto the results list without making changes. - If
new_titleis notNone, updates the task's title. - If
new_statusis notNone, updates the task's status. Ifnew_statusis not one of"new","pending", or"resolved", raises aValueError. - If successful, appends a copy of the updated task object to the results list.
- Finds the task with ID
-
delete:args = [task_id]- Removes the task with ID
task_idif it exists. - Appends
Trueif a task was found and deleted, orFalseif the ID did not exist.
- Removes the task with ID
Constraints
operationsandargumentshave the exact same length.- Operations will only be one of
"create","get","list","update", or"delete". - Task IDs are positive integers.
- If an operation raises a
ValueError, raising the standard PythonValueErrorexception is expected.
Examples
Example 1
Input: task_manager(['create', 'create', 'get', 'list', 'update', 'list', 'delete', 'get'], [['Buy milk'], ['Write report'], [1], [], [1, 'Buy oat milk', 'pending'], ['pending'], [2], [2]])
Output: [{'id': 1, 'title': 'Buy milk', 'status': 'new'}, {'id': 2, 'title': 'Write report', 'status': 'new'}, {'id': 1, 'title': 'Buy milk', 'status': 'new'}, [{'id': 1, 'title': 'Buy milk', 'status': 'new'}, {'id': 2, 'title': 'Write report', 'status': 'new'}], {'id': 1, 'title': 'Buy oat milk', 'status': 'pending'}, [{'id': 1, 'title': 'Buy oat milk', 'status': 'pending'}], True, None]
Example 2
Input: task_manager(['create', 'update', 'get', 'delete', 'get', 'list'], [['Fix bug'], [1, None, 'resolved'], [1], [1], [1], []])
Output: [{'id': 1, 'title': 'Fix bug', 'status': 'new'}, {'id': 1, 'title': 'Fix bug', 'status': 'resolved'}, {'id': 1, 'title': 'Fix bug', 'status': 'resolved'}, True, None, []]
Example 3
Input: task_manager(['list', 'create', 'list', 'update', 'list'], [[], ['Read book'], ['new'], [1, 'Read entire book', 'resolved'], ['resolved']])
Output: [[], {'id': 1, 'title': 'Read book', 'status': 'new'}, [{'id': 1, 'title': 'Read book', 'status': 'new'}], {'id': 1, 'title': 'Read entire book', 'status': 'resolved'}, [{'id': 1, 'title': 'Read entire book', 'status': 'resolved'}]]
Hints
Hint 1
Use a hash map (dictionary) mapping `task_id` to task objects for $O(1)$ lookups, along with an integer counter for ID generation.
Hint 2
Make sure to return copies of task dictionaries so that subsequent updates do not retroactively alter previously returned objects in the result list.
Hint 3
Validate that any provided `status` string belongs to the set `{'new', 'pending', 'resolved'}` when processing `list` or `update` operations.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to simulate an in-memory CRUD storage system for tasks. We can use a Python dictionary tasks mapping task_id to the corresponding task dictionary to achieve fast operations, alongside a counter next_id starting at 1.
For each operation in operations and its arguments in arguments:
create: Construct a dictionary{"id": next_id, "title": title, "status": "new"}. Store it intasks[next_id], append a copy of the dictionary to our results list, and incrementnext_id.get: Look up the task by ID intasks. If found, append a copy of it; otherwise, appendNone.list: Check if a status filter is provided. If a non-Nonefilter is provided and it is not in{"new", "pending", "resolved"}, raise aValueError. Filter all tasks currently intasksmatching the criterion, copy each, and append the resulting list to results.update: Check if the task ID exists intasks. If not, appendNone. If it exists, validate the new status if given (raisingValueErrorif invalid). Update the title and/or status as requested, then append a copy of the updated dictionary.delete: Remove the ID fromtasksusing.pop(task_id, None)and appendTrueif it existed, orFalseotherwise.
Complexity Analysis
- Time Complexity:
create,get,delete: $O(1)$ operations on dictionary lookups.update: $O(1)$ for lookup and field updates.list: $O(N)$ where $N$ is the number of active tasks, since we iterate through the dictionary values.- Overall time for $M$ operations: $O(M \cdot N)$ in the worst case.
- Space Complexity: $O(N + M)$ to store active tasks and construct the returned list of results.
Python 3 Reference Solution
from typing import List, Dict
def task_manager(operations: List[str], arguments: List[List]) -> List:
tasks: Dict[int, Dict] = {}
next_id = 1
results = []
valid_statuses = {"new", "pending", "resolved"}
for operation, args in zip(operations, arguments):
if operation == "create":
title = args[0]
task = {"id": next_id, "title": title, "status": "new"}
tasks[next_id] = task
results.append(task.copy())
next_id += 1
elif operation == "get":
task_id = args[0]
task = tasks.get(task_id)
results.append(task.copy() if task is not None else None)
elif operation == "list":
status = args[0] if args else None
if status is not None and status not in valid_statuses:
raise ValueError("invalid status")
listed = [
task.copy()
for task in tasks.values()
if status is None or task["status"] == status
]
results.append(listed)
elif operation == "update":
task_id, title, status = args
task = tasks.get(task_id)
if task is None:
results.append(None)
continue
if title is not None:
task["title"] = title
if status is not None:
if status not in valid_statuses:
raise ValueError("invalid status")
task["status"] = status
results.append(task.copy())
elif operation == "delete":
task_id = args[0]
results.append(tasks.pop(task_id, None) is not None)
else:
raise ValueError("unknown operation")
return results