Problem · Graph

Compilation Order with Topological Sort

MediumApplied IntuitionFULLTIMEONSITE INTERVIEW

You are given a list of module names and a list of dependency pairs. Each dependency [a, b] means module a depends on module b, so b must be compiled before a.

Return one valid compilation order that includes every module exactly once. If multiple modules are currently available to compile, choose the lexicographically smallest available module first so the result is deterministic.

If the dependency graph contains a cycle, return a single-element array ["IMPOSSIBLE"].

Function Description

Complete the function compilationOrder in the editor below.

compilationOrder has the following parameters:

  1. String[] modules: all module names
  2. String[][] dependencies: dependency pairs [module, prerequisite]

Returns

String[]: a valid compilation order, or ["IMPOSSIBLE"] if the dependencies contain a cycle.

Examples
01 · Example 1
modules = ["A", "B", "C", "D"]
dependencies = [["A", "B"], ["A", "C"], ["D", "A"]]
return = ["B", "C", "A", "D"]

Both B and C are initially available, so lexicographical order chooses B before C.

02 · Example 2
modules = ["A", "B"]
dependencies = [["A", "B"], ["B", "A"]]
return = ["IMPOSSIBLE"]

The two modules depend on each other, so no valid compilation order exists.

Constraints
  • 1 <= modules.length <= 2 * 10^5
  • 0 <= dependencies.length <= 2 * 10^5
  • All module names are distinct.
More Applied Intuition problems
drafts saved locally
public String[] compilationOrder(String[] modules, String[][] dependencies) {
    // write your code here
}
modules["A", "B", "C", "D"]
dependencies[["A", "B"], ["A", "C"], ["D", "A"]]
expected["B", "C", "A", "D"]
sign in to submit