- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 67 lines of C++ from the credited upstream file 2590.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Task {2 3 string taskDescription;4 int dueDate;5 unordered_set<string> tags;6 7 bool operator<(const Task& other) const {8 return dueDate < other.dueDate;9 }10};11 12class TodoList {13 public:14 int addTask(int userId, string taskDescription, int dueDate,15 vector<string> tags) {16 userIdToTaskIdToTasks[userId][++taskId] =17 Task{.taskDescription = taskDescription,18 .dueDate = dueDate,19 .tags = {tags.begin(), tags.end()}};20 taskIds.insert(taskId);21 return taskId;22 }23 24 vector<string> getAllTasks(int userId) {25 vector<string> res;26 for (const Task& task : getTasksSortedByDueDate(userId))27 res.push_back(task.taskDescription);28 return res;29 }30 31 vector<string> getTasksForTag(int userId, string tag) {32 vector<string> res;33 for (const Task& task : getTasksSortedByDueDate(userId))34 if (task.tags.contains(tag))35 res.push_back(task.taskDescription);36 return res;37 }38 39 void completeTask(int userId, int taskId) {40 if (!taskIds.contains(taskId))41 return;42 const auto it = userIdToTaskIdToTasks.find(userId);43 if (it == userIdToTaskIdToTasks.cend())44 return;45 auto& taskIdToTasks = it->second;46 if (!taskIdToTasks.contains(taskId))47 return;48 taskIdToTasks.erase(taskId);49 }50 51 private:52 int taskId = 0;53 unordered_set<int> taskIds;54 55 unordered_map<int, unordered_map<int, Task>> userIdToTaskIdToTasks;56 57 vector<Task> getTasksSortedByDueDate(int userId) {58 const auto it = userIdToTaskIdToTasks.find(userId);59 if (it == userIdToTaskIdToTasks.cend())60 return {};61 set<Task> tasks;62 for (const auto& [_, task] : it->second)63 tasks.insert(task);64 return {tasks.begin(), tasks.end()};65 }66};67