In this article
For a dependency-planning exercise, agree on what each edge means and whether invalid input may start any work. Build and validate the entire plan before execution, then test prerequisites and side effects independently. A valid order need not be the only valid order.
Define the failure contract before choosing an algorithm
Use this original exercise in a practice session where AI assistance is explicitly permitted. A small build service receives job names and their prerequisites. It must return a valid execution order, or reject the configuration before starting any job. Ask whether every prerequisite must be declared, whether disconnected jobs are allowed, and whether the caller requires one particular order. These answers determine both the implementation and what a useful test can assert.
For this exercise, names are strings, prerequisite lists contain strings, every referenced name must be a key, and independent jobs may appear in either order. Empty input is valid. A cycle or an unknown prerequisite is invalid. Parsing arbitrary JSON and handling worker failures are separate tasks. Write these decisions beside the function before asking an assistant for code; otherwise, a polished answer can solve a different scheduling problem without making that change obvious.
Explain the arrow using a concrete prerequisite
Suppose publish requires package, and package requires compile. The mapping stores publish with package in its prerequisite list. When drawing execution arrows, draw compile toward package, then package toward publish. Python TopologicalSorter accepts a mapping from each node to its predecessors. Confusing that input convention with a list of outgoing successors reverses the meaning of an otherwise reasonable implementation. Python graphlib: TopologicalSorter and CycleError
Add lint as an independent job. Now there are multiple acceptable outputs, so a test that insists lint must always appear first would introduce an unstated requirement. Explain the actual invariant aloud: each named job appears once, and every prerequisite appears before its dependent. That sentence gives the interviewer something concrete to challenge and gives the assistant a bounded target. Alphabetical sorting is immediately suspect because names do not encode dependencies.
Materialize a complete plan before starting jobs
The following illustrative implementation first rejects references outside the supplied graph. That check is deliberate: graphlib otherwise adds a predecessor that has not been separately declared. It then consumes static_order into a list and converts CycleError into the exercise error. Only run_jobs starts work, after plan_jobs returns successfully. The library provides the ordering and cycle detection; the surrounding function defines this application boundary. Python graphlib: TopologicalSorter and CycleError
Read the two phases as an explanation of ownership. Planning can fail without calling start. Execution receives an already accepted plan and visits its jobs sequentially. The list costs memory proportional to the number of jobs, which is reasonable for this small configuration exercise. Do not claim that it makes the work transactional: if start fails on the third job, the first two may already have completed. The promise is about invalid dependency configurations, not every possible runtime failure.
from graphlib import CycleError, TopologicalSorter
def plan_jobs(graph):
unknown = {dep for deps in graph.values() for dep in deps} - set(graph)
if unknown:
raise ValueError("unknown prerequisite")
try:
return list(TopologicalSorter(graph).static_order())
except CycleError as error:
raise ValueError("dependency cycle") from error
def run_jobs(graph, start):
order = plan_jobs(graph)
for name in order:
start(name)
return order
Reject repairs that silently discard impossible work
Give the assistant a graph where alpha requires beta, beta requires alpha, and lint has no prerequisites. A tempting repair catches a cycle, runs the independent job, and returns a partial result. That may be a useful feature elsewhere, but it violates this exercise: the caller asked for rejection before any job starts. Another tempting repair returns an empty list on failure. The caller can then mistake a rejected configuration for a valid empty workload.
A focused prompt is: review this planner for the stated all-or-reject preflight rule; show an input that would start work before rejection, or explain why that cannot happen. Ask for the affected call boundary rather than a general rewrite. If the suggested implementation supports partial progress, identify the behavior change explicitly. Keep that suggestion as a possible future requirement instead of quietly adopting it while retaining the original tests and explanation.
Verify edges and rejected work independently
Append this test block to the implementation and run the resulting Python file. The order checker builds positions from the result and checks the original prerequisites; it does not call the planner to manufacture an expected answer. The fixture adds archive after publish, making alphabetical sorting demonstrably wrong. Exact sequence equality remains appropriate for the empty result and the execution log, whose contracts are unambiguous.
The exception checks distinguish invalid input from successful emptiness. Python unittest provides assertRaisesRegex for checking the expected exception and message. The recorded start calls add a separate observation: rejecting a cycle is insufficient if work already began. These checks deliberately cover a self-loop, a multi-job cycle, an unknown prerequisite, and a normal graph. Passing them supports those behaviors; it does not establish correctness for every configuration. Python unittest: assertions and exception checks
import unittest
def respects_dependencies(graph, order):
if len(order) != len(graph) or set(order) != set(graph):
return False
position = {name: index for index, name in enumerate(order)}
return all(position[dep] < position[name]
for name, deps in graph.items() for dep in deps)
class PlannerTests(unittest.TestCase):
def test_valid_order_and_wrong_alternative(self):
graph = {"publish": ["package"], "package": ["compile"],
"compile": [], "lint": [], "archive": ["publish"]}
self.assertTrue(respects_dependencies(graph, plan_jobs(graph)))
self.assertFalse(respects_dependencies(graph, sorted(graph)))
def test_cycle_starts_nothing(self):
started = []
with self.assertRaisesRegex(ValueError, "dependency cycle"):
run_jobs({"alpha": ["beta"], "beta": ["alpha"], "lint": []},
started.append)
self.assertEqual(started, [])
def test_self_loop(self):
with self.assertRaisesRegex(ValueError, "dependency cycle"):
plan_jobs({"build": ["build"]})
def test_unknown_prerequisite(self):
with self.assertRaisesRegex(ValueError, "unknown prerequisite"):
plan_jobs({"publish": ["missing"]})
def test_empty_graph(self):
self.assertEqual(plan_jobs({}), [])
def test_execution_follows_plan(self):
graph = {"ship": ["test"], "test": []}
started = []
order = run_jobs(graph, started.append)
self.assertEqual(started, ["test", "ship"])
self.assertEqual(order, started)
if __name__ == "__main__":
unittest.main()
Finish with the verified guarantee and its limits
An illustrative closing explanation is: I rejected undeclared prerequisites, built the full dependency order, and then started jobs. The cycle case records zero starts. The valid case checks every prerequisite relationship without assuming one order for independent jobs. This is a more useful handoff than saying the library handles everything, because it identifies the application policy you added and the evidence you collected.
If the interviewer asks for concurrent workers next, revisit the contract before extending the code. Readiness and successful completion become different states, and a failed prerequisite may prevent dependents from starting. If they ask for deterministic tie breaking, add a stated ordering rule and matching tests. Neither follow-up should be claimed as already solved by this sequential planner. The useful interview skill is keeping your explanation aligned with the behavior you actually implemented.
Common questions about dependency-planning interviews
Should I always use a library in an interview? Confirm the exercise rules. If implementing the ordering algorithm is the task, a library call may miss the point. You can still use the same graph contract, failure cases, and independent order checker while implementing the algorithm yourself. Ask that question before investing in an approach.
Is a cycle the same as a missing job? No. A cycle contains declared jobs that cannot satisfy each other first. An unknown prerequisite references a name the exercise does not define. Separate errors make those failures explainable. Does this guarantee rollback? No. It prevents execution for invalid graphs; compensation for jobs that fail during execution needs its own design.
Sources & editorial notes
This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.
- Python graphlib: TopologicalSorter and CycleError
Checked November 29, 2026. Documents predecessor mappings, implicit nodes, ordering, and cycle errors; cited as reference documentation, not a new announcement.
- Python unittest: assertions and exception checks
Checked November 29, 2026. Documents unittest assertions used for independently chosen expected values and rejected inputs.
Put the reading into practice
Work through an existing repository, review AI suggestions, and test the decisions behind your changes.
Explore practice problems