progress

~/problems / Graphs / Topological sort (Kahn's)

What to rebuild, and in what order

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

A build tool keeps a dependency map: deps[target] lists what target is built from. Inputs can be targets or source files (a source file never appears as a key). There are no cycles.

Some files were just edited. They must be rebuilt, along with everything that directly or indirectly uses them; nothing else.

Implement rebuild_order(deps: dict[str, list[str]], changed: list[str]) -> list[str]:

  • Return every affected name exactly once, each after all of its inputs that are also in the list. Any such order is accepted.
  • changed may repeat a name or name something nobody uses.
deps = {
    "app":    ["lib", "ui"],
    "lib":    ["util.c", "math.c"],
    "ui":     ["theme.css"],
    "tests":  ["lib"],
}
rebuild_order(deps, ["math.c"])
# ["math.c", "lib", "app", "tests"]    ("tests" before "app" is fine too; "ui" is untouched)
The dependency map drawn from inputs to users: editing math.c forces lib, then app and tests, to rebuild, while util.c, theme.css and ui stay untouched.
Arrows point from an input to the targets that use it.
deps = {
    "app":    ["lib", "ui"],
    "lib":    ["util.c", "math.c"],
    "ui":     ["theme.css"],
    "tests":  ["lib"],
}
rebuild_order(deps, ["theme.css", "util.c"])
# e.g. ["theme.css", "util.c", "ui", "lib", "app", "tests"]

Up to 10^5 names and 2 * 10^5 links.

⭐ Bonus: a speed test with a 100,000-long chain earns a star in O(names + links), without recursion or rescanning all targets each time you place one.

Show hint

reverse the edges (input -> users), BFS from the changed names to find the affected set, then run Kahn's algorithm counting only in-edges from inside that set.

Topic: Topological sort (Kahn's). BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc