Approach
Sorting and greedy selection
For Design a Todo List, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 51 lines of Python from the credited upstream file 2590.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass(frozen=True)5class Task:6 taskDescription: str7 dueDate: int8 tags: list[str]9 10 11class TodoList:12 def __init__(self):13 self.taskId = 014 self.taskIds = set()15 self.userIdToTaskIdToTasks: dict[int, dict[int, list[Task]]] = {}16 17 def addTask(self, userId: int, taskDescription: str, dueDate: int,18 tags: list[str]) -> int:19 self.taskId += 120 taskIdToTasks = self.userIdToTaskIdToTasks.setdefault(userId, {})21 taskIdToTasks[self.taskId] = Task(taskDescription, dueDate, tags)22 self.taskIds.add(self.taskId)23 return self.taskId24 25 def getAllTasks(self, userId: int) -> list[str]:26 return [task.taskDescription27 for task in self._getTasksSortedByDueDate(userId)]28 29 def getTasksForTag(self, userId: int, tag: str) -> list[str]:30 return [task.taskDescription31 for task in self._getTasksSortedByDueDate(userId)32 if tag in task.tags]33 34 def completeTask(self, userId: int, taskId: int) -> None:35 if taskId not in self.taskIds:36 return37 if userId not in self.userIdToTaskIdToTasks:38 return39 taskIdToTasks = self.userIdToTaskIdToTasks[userId]40 if taskId not in taskIdToTasks:41 return42 del taskIdToTasks[taskId]43 44 def _getTasksSortedByDueDate(self, userId: int) -> list[Task]:45 if userId not in self.userIdToTaskIdToTasks:46 return []47 taskIdToTasks = self.userIdToTaskIdToTasks[userId]48 return sorted(49 [task for task in taskIdToTasks.values()],50 key=lambda x: x.dueDate)51