795. Build a todo list that tracks dependencies between tasks
An agent working through a plan needs a todo list that knows which tasks are blocked by others, so it can always ask what it is allowed to do next.
Write run_todo(ops). ops is a list of tuples:
('add', id, deps) adds an open task that depends on every id in the list deps. Output 'ERROR' if id exists or any dep is unknown. ('depend', a, b) makes task a also depend on task b. Output 'ERROR' if either id is unknown or a is already done, and output 'CYCLE' (and change nothing) if this would create a cycle, including a == b. ('done', id) marks the task done; output 'BLOCKED' (and change nothing) if any of its dependencies is not done, 'ERROR' if the id is unknown. Marking a done task done again does nothing. ('ready',) outputs the sorted list of open tasks whose dependencies are all done. ('order',) outputs an order for all open tasks that respects dependencies, always picking the smallest available id next.
Return the list of outputs in order.
def run_todo(ops)Example 1
Input: run_todo([('add', 'b', []), ('add', 'a', ['b']), ('ready',), ('done', 'a'), ('done', 'b'), ('ready',)])
Output: [['b'], 'BLOCKED', ['a']]
Constraints
- Up to 2,000 tasks.
- Ids are strings compared with normal string order.
Hint 1
Store deps as sets per task.
Hint 2
Cycle check: can you reach a from b?
Hint 3
Kahn's algorithm with a heap gives the smallest-first order.
Common mistakes
- Checking the cycle in the wrong direction.
- Adding the edge before checking and forgetting to undo it.
- Counting done dependencies as blockers in order.
Understand the idea
A dependency graph with readiness queries, cycle prevention and topological ordering.