Problem 593906 · medium · Phase 05 Advanced Algorithms & Graphs

Project Build Order

topological sort · hash maps · string keys

You are given a list of project names projects (distinct strings) and a list deps of pairs [a, b] meaning project a must be built before project b. Every name in deps appears in projects.

Return a list containing every project exactly once, in an order that satisfies all dependencies. If several orders are valid, return any. If no order exists, return None.

Examples

Input:  projects = ["a", "b", "c", "d"], deps = [["a", "d"], ["b", "d"], ["d", "c"]]
Output: ["a", "b", "d", "c"]
Explanation: ["b", "a", "d", "c"] is also accepted.

Input:  projects = ["x", "y"], deps = [["x", "y"], ["y", "x"]]
Output: None

Constraints

  • 0 <= len(projects) <= 5000, 0 <= len(deps) <= 10**4
  • Target: O(V + E) time.

Goals

  • Run a topological sort on string-named nodes
  • Return None when dependencies are contradictory
Starting Python…