Detect Circular Dependencies in a Build System
Trees & GraphsAuto-graded · 17 test casesLast 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 fromatob. - 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 nodeais in a cycle.
Constraints
1 <= n <= 20000 <= len(edges) <= 5000- Each edge is a list
[a, b]where0 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
We use a DFS with a recursion stack (a classic cycle-detection technique for directed graphs). During DFS, we maintain:
- A
statearray: each node is unvisited (0), on the current DFS path/stack (1), or fully processed (2). - An explicit
stacklist that tracks the current DFS path (in order).
When we visit a neighbor that is currently on the stack (state = 1), we have found a back edge, which confirms a directed cycle. The cycle consists of all nodes from the neighbor's position in the stack up to the current node.
We mark every node in that segment as being "in a cycle."
Why It Is Correct
- Every directed cycle must contain at least one back edge when traversed with DFS (this is a standard theorem for directed graphs).
- When we detect a back edge to node
v, the cycle is precisely the portion of the current DFS stack fromvto the top. Marking all those nodes correctly identifies every participant in the cycle. - We deduplicate input edges using sets, so duplicate edges do not affect correctness.
- Self-loops are handled naturally: the neighbor equals the current node, which is already on the stack with state = 1.
- After all DFS calls complete, we collect and sort the marked nodes.
Complexity
- Time: O(n + E) for the DFS traversal, where E is the number of unique edges. The
stack.index()call is O(n) in the worst case but occurs at most E times, so the overall worst-case is O(n · E). In practice (sparse graphs), this is fine for n, E ≤ 2000/5000. An O(n + E) variant can be achieved by storing each node's stack index in a dict. - Space: O(n + E) for the adjacency list, state array, and recursion stack.
Reference Solution
from typing import List
def find_cycle_nodes(n: int, edges: List[List[int]]) -> List[int]:
# Build adjacency list, deduplicating edges
adj = [set() for _ in range(n)]
for a, b in edges:
adj[a].add(b)
# 0 = unvisited, 1 = in current stack, 2 = fully processed
state = [0] * n
in_cycle = [False] * n
def dfs(node: int, stack: list) -> None:
state[node] = 1
stack.append(node)
for neighbor in adj[node]:
if state[neighbor] == 1:
# Found a back edge — mark all nodes on the cycle
idx = stack.index(neighbor)
for cycle_node in stack[idx:]:
in_cycle[cycle_node] = True
elif state[neighbor] == 0:
dfs(neighbor, stack)
stack.pop()
state[node] = 2
for start in range(n):
if state[start] == 0:
dfs(start, [])
return [i for i in range(n) if in_cycle[i]]