Problem 593906 · medium · Level 05 Advanced Algorithms & Graphs

Which Job Comes First on the Building Site?

topological sort · hash maps · string keys

A building site has a list of jobs projects (distinct names) and a list deps of pairs [a, b], each saying that job a has to be finished before job b can start. Every name in deps is one of the jobs.

Return a schedule: a list containing every job exactly once, in an order that respects every pair. If several schedules work, return any of them. If the pairs cannot all be met (some jobs wait on each other in a loop), return None.

Examples

Input:  projects = ["walls", "roof", "plumbing", "paint"], deps = [["walls", "roof"], ["walls", "plumbing"], ["plumbing", "paint"]]
Output: ["walls", "roof", "plumbing", "paint"]
Explanation: ["walls", "plumbing", "paint", "roof"] 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…