call(back)
Algorithms & Data StructuresmediumSign in to star problems

Workflow With Dependencies

Build a small workflow of named tasks and the dependencies between them:

workflow = Workflow()
workflow.addTask(name)                  // a new task; a name already present is left alone
workflow.addDependency(task, dependsOn) // task may run only after dependsOn; true if recorded
workflow.order()                        // every task, each after everything it depends on
workflow.deepCopy()                     // an independent Workflow with the same tasks and dependencies

Rules

  • A dependency that would create a cycle, including a task depending on itself, is refused: addDependency returns false and records nothing. Both names must already be tasks.
  • order() is deterministic: whenever more than one task is ready, the one added first goes next. With no dependencies it is the insertion order.
  • Changes to a copy never show in the original, and the other way round.
addTask("build") · addTask("test") · addTask("deploy")
addDependency("test", "build")    ->  true
addDependency("deploy", "test")   ->  true
addDependency("build", "deploy")  ->  false     // would close a cycle
order()                           ->  ["build", "test", "deploy"]

Hints

Hint 1

Keep the tasks in an array for insertion order and a map from task to the set of tasks it depends on. A new dependency task → dependsOn closes a cycle exactly when dependsOn already depends on task, directly or transitively; one depth-first search from dependsOn answers that.

Hint 2

For the order, count each task's unmet dependencies and repeatedly take the earliest-added task whose count is zero; when it is emitted, decrement every task that depends on it. The copy is a fresh Workflow fed the same tasks and the same dependency pairs.

Topics

Asked at

Similar Problems6