- 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
- 50 lines of Java from the credited upstream file 2590.java.
- 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.
1class TodoList {2 public int addTask(int userId, String taskDescription, int dueDate, List<String> tags) {3 userIdToTaskIdToTasks.putIfAbsent(userId, new HashMap<>());4 userIdToTaskIdToTasks.get(userId).put(++taskId, new Task(taskDescription, dueDate, tags));5 taskIds.add(taskId);6 return taskId;7 }8 9 public List<String> getAllTasks(int userId) {10 List<String> res = new ArrayList<>();11 for (Task task : getTasksSortedByDueDate(userId))12 res.add(task.taskDescription);13 return res;14 }15 16 public List<String> getTasksForTag(int userId, String tag) {17 List<String> res = new ArrayList<>();18 for (Task task : getTasksSortedByDueDate(userId))19 if (task.tags.contains(tag))20 res.add(task.taskDescription);21 return res;22 }23 24 public void completeTask(int userId, int taskId) {25 if (!taskIds.contains(taskId))26 return;27 if (!userIdToTaskIdToTasks.containsKey(userId))28 return;29 Map<Integer, Task> taskIdToTasks = userIdToTaskIdToTasks.get(userId);30 if (!taskIdToTasks.containsKey(taskId))31 return;32 taskIdToTasks.remove(taskId);33 }34 35 private record Task(String taskDescription, int dueDate, List<String> tags) {}36 private int taskId = 0;37 private Set<Integer> taskIds = new HashSet<>();38 39 private Map<Integer, Map<Integer, Task>> userIdToTaskIdToTasks = new HashMap<>();40 41 private List<Task> getTasksSortedByDueDate(int userId) {42 if (!userIdToTaskIdToTasks.containsKey(userId))43 return new ArrayList<>();44 TreeSet<Task> tasks = new TreeSet<>(Comparator.comparingInt(Task::dueDate));45 for (Task task : userIdToTaskIdToTasks.get(userId).values())46 tasks.add(task);47 return new ArrayList<>(tasks);48 }49}50