KatInterview

Task Scheduling Order and Undoable Command Pipeline

Data Structure DesignModel answer
MediumModel answerData Structure Designtrees-graphsdesign-dsstacks-queues

Last updated

Resolve prerequisite-constrained task sequences with cycle detection, then construct an extensible Command pattern system with state rollback functionality.

This two-part problem tests graph scheduling and object-oriented behavioral design.

Section 1: Task Dependency Resolution

Write a function schedule_tasks(tasks, dependencies) that takes a set of distinct task identifiers and a list of directed pairs (prerequisite, target).

  • Each pair (A, B) means task A must finish before task B can begin.
  • Return a list representing a valid linear sequence where every task appears only after all its prerequisites have run.
  • If a valid sequence cannot be generated due to circular dependencies, return None.

Section 2: Reversible Command Engine

Design and implement a thread-safe execution engine supporting command execution and undo capabilities over a key-value dictionary state.

Requirements:

  1. Define a clear interface for commands that mutate a shared dict state.
  2. Implement a TaskExecutor class with two main operations:
    • execute(command): Runs the command on the state dictionary and tracks it for future rollback.
    • undo(): Reverts the state back to what it was prior to running the most recent active command.
  3. Handle failure scenarios cleanly (e.g., calling undo() on an empty action log, or handling failed command executions).
  4. Demonstrate this pattern with concrete command implementations (e.g., setting a key, deleting a key, or applying an arithmetic modification).