KatInterview

Detect Circular Dependencies in a Build System

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphscycle detectionDFS

Last updated

Tests cycle detection in a directed graph by determining which packages in a build dependency graph are part of a circular dependency chain.

Detect Circular Dependencies in a Build System

A build system manages a collection of packages numbered 0 through n - 1. Each package may declare that it must be built before another package — a directed dependency edge from package a to package b means "package a must be built before package b" (i.e., b depends on a).

A circular dependency occurs when a set of packages form a cycle in this directed graph: package X (directly or transitively) depends on itself.

Given n packages and a list of directed edges, return a sorted list of all package indices that are part of at least one cycle. If no cycle exists, return an empty list.

Definitions

  • An edge [a, b] means there is a directed edge from a to b.
  • A node is considered "in a cycle" if it lies on at least one directed cycle in the graph.
  • Duplicate edges may appear in the input and should be treated as a single edge.
  • Self-loops (an edge [a, a]) count as a cycle; the node a is in a cycle.

Constraints

  • 1 <= n <= 2000
  • 0 <= len(edges) <= 5000
  • Each edge is a list [a, b] where 0 <= a, b < n
  • The returned list must be sorted in ascending order.

Examples

Example 1

Input: find_cycle_nodes(4, [[0, 1], [1, 2], [2, 0], [3, 0]])

Output: [0, 1, 2]

Example 2

Input: find_cycle_nodes(3, [[0, 1], [1, 2], [2, 0]])

Output: [0, 1, 2]

Example 3

Input: find_cycle_nodes(4, [[0, 1], [1, 2], [2, 3]])

Output: []

Hints

Hint 1

Try a DFS-based approach that tracks nodes currently on the recursion stack — any back edge you find reveals a cycle.

Hint 2

When you find a cycle, you need to mark every node on the cycle, not just the two endpoints of the back edge. Think about what portion of the current DFS stack is part of the cycle.

Hint 3

After collecting all cycle nodes during DFS, remember to deduplicate and sort the result. Self-loops are a special case worth handling explicitly before the main DFS.