Problem 597247 · easy · Phase 05 Advanced Algorithms & Graphs

Is the Build Graph Acyclic?

topological sort · directed graphs · cycle detection

A build system is described by a dictionary deps. Each key is the name of a target (a string) and its value is a list of target names that must be built before it. A name that only appears inside a value list (never as a key) is a leaf target with no dependencies of its own.

Return True if every target can be built, i.e. the dependency graph has no cycle, and False otherwise. A target that depends on itself is a cycle.

Examples

Input:  deps = {"app": ["lib", "util"], "lib": ["util"]}
Output: True
Explanation: build util, then lib, then app.

Input:  deps = {"a": ["b"], "b": ["a"]}
Output: False

Constraints

  • 0 <= number of targets <= 10**4, total list length <= 2 * 10**4
  • Target: O(V + E) time

Goals

  • Collect the node set from both keys and values of a dependency map
  • Use in-degree peeling to decide whether every node can be scheduled
Starting Python…