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.
changedmay 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)
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.