Compilation Order

curriculum-track — return a valid build order for projects given their dependencies via topological sort.

Medium
Time O(V + E) Space O(V + E)
4 min read
topological-sort graph

Problem#

(curriculum variant.) Given projects (string names) and dependency pairs [a, b] meaning “a must be built before b”, return any valid build order. Return [] if impossible.

Examples#

  • projects = ["a","b","c","d","e","f"], deps = [["a","d"],["f","b"],["b","d"],["f","a"],["d","c"]]["e","f","a","b","d","c"]

Approach#

Standard Kahn’s BFS over the dependency DAG.

Solution#

Compilation Order
vector<string> compilationOrder(vector<string> projects, vector<pair<string,string>> deps) {
unordered_map<string, vector<string>> adj;
unordered_map<string, int> indeg;
for (auto& p : projects) indeg[p];
for (auto& [a, b] : deps) {
adj[a].push_back(b);
++indeg[b];
}
queue<string> q;
for (auto& p : projects) if (indeg[p] == 0) q.push(p);
vector<string> out;
while (!q.empty()) {
string u = q.front(); q.pop();
out.push_back(u);
for (auto& v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return (int)out.size() == (int)projects.size() ? out : vector<string>{};
}

Editorial#

Same Kahn’s BFS as Course Schedule II. Build dependency DAG, enumerate zero-indegree, process and decrement.

Complexity#

  • Time: O(V + E).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.