Design a Todo List — LeetCode 2590 Python Solution
MediumLeetCode PremiumDesignArrayHash TableStringSorting
- Problem
- #2590
- Pattern
- Sorting
- Reading time
- 7 min
- Source
- leetcode.com
The problem
Design a Todo List Where users can add tasks, mark them as complete, or get a list of pending tasks. Users can also add tags to tasks and can filter the tasks by certain tags.
Example
- Input
- ["TodoList", "addTask", "addTask", "getAllTasks", "getAllTasks", "addTask", "getTasksForTag", "completeTask", "completeTask", "getTasksForTag", "getAllTasks"]
- Output
- [null, 1, 2, ["Task1", "Task2"], [], 3, ["Task3", "Task2"], null, null, ["Task3"], ["Task3", "Task1"]]
- Explanation
- TodoList todoList = new TodoList();
Python solution
Python
class TodoList:
def __init__(self):
self.i = 1
self.tasks = defaultdict(SortedList)
def addTask(
self, userId: int, taskDescription: str, dueDate: int, tags: List[str]
) -> int:
taskId = self.i
self.i += 1
self.tasks[userId].add([dueDate, taskDescription, set(tags), taskId, False])
return taskId
def getAllTasks(self, userId: int) -> List[str]:
return [x[1] for x in self.tasks[userId] if not x[4]]
def getTasksForTag(self, userId: int, tag: str) -> List[str]:
return [x[1] for x in self.tasks[userId] if not x[4] and tag in x[2]]
def completeTask(self, userId: int, taskId: int) -> None:
for task in self.tasks[userId]:
if task[3] == taskId:
task[4] = True
break
# Your TodoList object will be instantiated and called as such:
# obj = TodoList()
# param_1 = obj.addTask(userId,taskDescription,dueDate,tags)
# param_2 = obj.getAllTasks(userId)
# param_3 = obj.getTasksForTag(userId,tag)
# obj.completeTask(userId,taskId)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2590. Design a Todo List is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2590. Design a Todo List?
- LeetCode 2590. Design a Todo List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2590. Design a Todo List?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2590. Design a Todo List?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2590. Design a Todo List cover?
- LeetCode 2590. Design a Todo List is tagged Design, Array, Hash Table, String and Sorting on LeetCode.
- Is LeetCode 2590. Design a Todo List a premium problem?
- Yes. LeetCode 2590. Design a Todo List is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.