← All Exercises

Deterministic Topological Sort for Dependencies

advancedjavascript~15min

Background

Build systems, package managers, and task runners need a dependency order. Kahn's algorithm produces one, and a sorted ready set makes the output reproducible for caching and diffing.

Problem

Implement topologicalSort(nodes, edges) where each edge [a, b] means a depends on b. Return dependencies before dependents, choosing alphabetically among ready nodes so the result is deterministic. If a cycle prevents processing every node, return an empty order and cycle:true.

Input

A JSON object with nodes (unique names) and edges as [dependent, dependency] pairs.

Output

A JSON object with order (all node names, or an empty array on a cycle) and cycle (boolean).

Sample tests

Sample 1

Input: {"nodes":["app","lib","core","docs"],"edges":[["app","lib"],["app","core"],["lib","core"],["docs","core"]]}
Expected: {"order":["core","docs","lib","app"],"cycle":false}

Sample 2

Input: {"nodes":["b","a","c"],"edges":[]}
Expected: {"order":["a","b","c"],"cycle":false}

Sample 3

Input: {"nodes":["a","b"],"edges":[["a","b"],["b","a"]]}
Expected: {"order":[],"cycle":true}

Sample 4

Input: {"nodes":["d","b","c","a"],"edges":[["d","b"],["d","c"],["b","a"],["c","a"]]}
Expected: {"order":["a","b","c","d"],"cycle":false}

Your solution

Learning objective

Understand Kahn's algorithm, deterministic tie-breaking, and cycle detection in dependency graphs.