Compilation Order

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given a list of source files and their dependencies represented as pairs [file, dependency], meaning that file depends on dependency and dependency must be compiled before file.

Return a valid compilation order such that every file is compiled after all of its dependencies. If there are multiple valid orderings, return any of them.

You may assume that the dependency graph has no cycles and that a valid compilation order always exists.

Examples

Example 1:

Input: dependencies = [["B","A"],["C","A"],["D","B"],["D","C"]]

Output: ["A","B","C","D"]

Explanation: A has no dependencies so it is compiled first. B and C both depend on A. D depends on both B and C. A valid order is ["A", "B", "C", "D"] or ["A", "C", "B", "D"].

Example 2:

Input: dependencies = [["B","A"],["C","B"],["D","C"]]

Output: ["A","B","C","D"]

Explanation: The files form a chain: A → B → C → D. The only valid order is ["A", "B", "C", "D"].

Example 3:

Input: dependencies = [["B","A"],["C","A"],["D","A"]]

Output: ["A","B","C","D"]

Explanation: B, C, and D all depend only on A. After compiling A, the rest can be compiled in any order.

Constraints

  • 1 <= dependencies.length <= 1000
  • dependencies[i].length == 2
  • Each element is a non-empty string
  • The dependency graph contains no cycles
Source: Topological Sort pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle