Skip to content

Conversation

@luckyb13
Copy link
Contributor

Pull Request: Add Topological Sort with Cycle Detection (topoSort.js)

Changes Made

  • Added topoSort.js, a utility for topological sorting with explicit cycle detection.
  • Supports two input shapes: adjacency-list object and edge list. Outputs a valid topological order or throws with cycle details.
  • Added topoLevels to group nodes by dependency levels using Kahn's algorithm.

Implementation Summary

  • toGraph(input): normalizes input into an adjacency list and ensures all nodes are present.
  • topoSort(input): DFS-based sort with a three-color state (unvisited/visiting/done). Detects cycles and throws an Error with a human-readable cycle path.
  • topoLevels(input): Kahn’s algorithm variant that returns levels (sources first). Throws on cycles by delegating to topoSort.
  • Complexity: O(V + E) time, O(V + E) space.

Usage Example

// Edges form: [from, to]
import { topoSort, topoLevels } from "./topoSort.js";

const edges = [["a","b"],["a","c"],["b","d"],["c","d"]];
const order = topoSort(edges); // ["a","b","c","d"] or ["a","c","b","d"]
const levels = topoLevels({ a:["b","c"], b:["d"], c:["d"], d:[] });
// levels = [["a"], ["b","c"], ["d"]]

Validation

  • Handles both adjacency-list and edge-list inputs.
  • Ensures nodes with no outgoing edges appear in the graph.
  • Throws with a readable cycle trace when a back-edge is found.

Notes for Reviewers

  • No external dependencies; works in Node and browsers.
  • Clear separation of concerns: normalization, DFS sort, Kahn levels.
  • JSDoc types for better DX and autocomplete.

This contribution is substantive and improves the repository’s algorithms coverage. Please add the label:

hacktoberfest-accepted

Thank you.

@ghostmkg ghostmkg merged commit fec9e1f into ghostmkg:main Oct 31, 2025
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants