Task Scheduling Order and Undoable Command Pipeline
Data Structure DesignModel answerLast 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 taskAmust finish before taskBcan 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:
- Define a clear interface for commands that mutate a shared
dictstate. - Implement a
TaskExecutorclass 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.
- Handle failure scenarios cleanly (e.g., calling
undo()on an empty action log, or handling failed command executions). - Demonstrate this pattern with concrete command implementations (e.g., setting a key, deleting a key, or applying an arithmetic modification).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task Scheduling Order and Undoable Command Pipeline
Part 1: Task Dependency Resolution
Approach & Implementation
We model task dependencies as a directed graph where an edge $A \to B$ indicates that $A$ is a prerequisite for $B$. Finding a valid execution sequence is equivalent to obtaining a topological ordering of the Directed Acyclic Graph (DAG).
We implement Kahn's Algorithm (BFS-based):
- Construct an in-degree map tracking how many unmet prerequisites each task has.
- Initialize a double-ended queue with all tasks that have an in-degree of
0(ready for immediate execution). - Process nodes sequentially: pop a task, record it in the output sequence, and decrease the in-degree of all target nodes dependent on it. If a target's in-degree reaches
0, append it to the queue. - If the final output sequence contains all uniquely identified tasks, the schedule is valid. Otherwise, a circular dependency exists, and we return
None.
from collections import defaultdict, deque
from typing import Any, List, Optional, Set, Tuple
def schedule_tasks(
tasks: Iterable[Any],
dependencies: List[Tuple[Any, Any]]
) -> Optional[List[Any]]:
"""
Computes a valid execution sequence for tasks with prerequisites.
:param tasks: Collection of all task identifiers.
:param dependencies: List of (prereq, target) tuples.
:return: List of tasks in executable order, or None if a cycle is present.
"""
# Track all unique nodes present in input or dependencies
graph = defaultdict(list)
in_degree = {task: 0 for task in tasks}
for prereq, target in dependencies:
in_degree.setdefault(prereq, 0)
in_degree.setdefault(target, 0)
graph[prereq].append(target)
in_degree[target] += 1
# Queue all nodes that have no prerequisites
ready_queue = deque([node for node, count in in_degree.items() if count == 0])
ordered_sequence = []
while ready_queue:
current = ready_queue.popleft()
ordered_sequence.append(current)
for neighbor in graph[current]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
ready_queue.append(neighbor)
# If output length does not match total nodes, a cycle was encountered
if len(ordered_sequence) != len(in_degree):
return None
return ordered_sequence
Complexity Analysis
- Time Complexity: $\mathcal{O}(V + E)$, where $V$ is the number of distinct tasks and $E$ is the number of dependency relationships. Every task and dependency edge is evaluated at most once.
- Space Complexity: $\mathcal{O}(V + E)$ to maintain the adjacency list, in-degree dictionary, and BFS queue.
Part 2: Reversible Command Engine
Architecture & Design Choice
To maintain audit history and allow rollbacks, we utilize the Command Pattern in combination with a LIFO History Stack.
- State Isolation & Memento Pattern: Each concrete command captures the minimal state required to reverse itself (Memento) right before applying mutations during
execute(). For state updates (e.g., updating dictionary key-value pairs), saving previous key values rather than deep-copying the entire application state optimizes memory usage. - Atomic Execution: A command is pushed to the history stack only after
execute()succeeds without raising exceptions. - Thread Safety: Synchronization primitives (
threading.Lock) safeguard the executor history stack and state mutations against race conditions in multi-threaded runtime environments.
Concrete Implementation
from abc import ABC, abstractmethod
from threading import Lock
from typing import Any, Dict, List, Optional
# Sentinel object to distinguish non-existent keys from None values
_UNDEFINED = object()
class AbstractCommand(ABC):
"""Base interface for executable and reversible commands."""
@abstractmethod
def execute(self, state: Dict[str, Any]) -> None:
"""Mutates state dictionary while saving pre-execution context."""
pass
@abstractmethod
def undo(self, state: Dict[str, Any]) -> None:
"""Restores state dictionary using saved pre-execution context."""
pass
class SetValueCommand(AbstractCommand):
"""Sets a specified key-value pair in state."""
def __init__(self, key: str, value: Any):
self.key = key
self.value = value
self._prev_value: Any = _UNDEFINED
def execute(self, state: Dict[str, Any]) -> None:
self._prev_value = state.get(self.key, _UNDEFINED)
state[self.key] = self.value
def undo(self, state: Dict[str, Any]) -> None:
if self._prev_value is _UNDEFINED:
state.pop(self.key, None)
else:
state[self.key] = self._prev_value
class DeleteKeyCommand(AbstractCommand):
"""Deletes a key from the state dictionary."""
def __init__(self, key: str):
self.key = key
self._prev_value: Any = _UNDEFINED
def execute(self, state: Dict[str, Any]) -> None:
if self.key not in state:
raise KeyError(f"Cannot delete non-existent key: '{self.key}'")
self._prev_value = state[self.key]
del state[self.key]
def undo(self, state: Dict[str, Any]) -> None:
if self._prev_value is not _UNDEFINED:
state[self.key] = self._prev_value
class TaskExecutor:
"""Manages command invocation and rollback stack."""
def __init__(self, initial_state: Optional[Dict[str, Any]] = None):
self._state: Dict[str, Any] = initial_state if initial_state is not None else {}
self._history: List[AbstractCommand] = []
self._lock = Lock()
def execute(self, command: AbstractCommand) -> None:
"""Runs a command safely and pushes it to history upon success."""
with self._lock:
command.execute(self._state)
self._history.append(command)
def undo(self) -> bool:
"""
Reverts the latest command from history.
:return: True if an action was undone, False if history is empty.
"""
with self._lock:
if not self._history:
return False
last_command = self._history.pop()
try:
last_command.undo(self._state)
except Exception:
# If undo fails, push the command back to retain consistent stack state
self._history.append(last_command)
raise
return True
@property
def state(self) -> Dict[str, Any]:
"""Returns a snapshot copy of current state."""
with self._lock:
return dict(self._state)
Key Considerations & Trade-Offs
- Undo Capabilities with Missing Keys: Using a custom sentinel (
_UNDEFINED = object()) ensures that a key storing a literal value ofNoneis distinguished from a non-existent key. - Redo Stack Support (Follow-Up): Redo capabilities can be added by maintaining a second
_redo_stack. Executingundo()pushes the reverted command to_redo_stack. Invokingexecute()clears_redo_stackbecause executing a new branch invalidates previous redo history. - Memory Management: For long-running execution engines, unlimited command stacks cause memory leaks. Memory usage can be capped by replacing
_historylist withcollections.deque(maxlen=K).