Detect Cycles in a Package Dependency Graph
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests ability to detect cycles in a directed graph using DFS-based cycle detection, modelling package dependencies where a cycle makes installation impossible.
Package Dependency Validator
You are building a package manager. Each package may declare that it must be installed before certain other packages. Given a list of such "must come before" rules, determine whether it is possible to install all packages without contradiction.
A contradiction occurs when the dependency rules form a cycle — for example, package A requires B, B requires C, and C requires A again. In that case, it is impossible to satisfy all requirements.
You are given:
n— the total number of packages, identified by integers0throughn - 1.dependencies— a list of pairs[a, b]meaning packageamust be installed before packageb.
Return True if the packages can all be installed (no cycle exists), or False if a cycle makes it impossible.
Notes
- There may be packages with no dependencies at all.
- There may be duplicate dependency pairs in the input; treat them as a single edge.
- The graph may be disconnected (some packages are independent of others).
- Self-loops (a pair
[a, a]) count as a cycle.
Constraints
1 <= n <= 20000 <= len(dependencies) <= 10000- Each pair
[a, b]satisfies0 <= a, b <= n - 1
Examples
Example 1
Input: can_install_all(4, [[0, 1], [1, 2], [2, 3]])
Output: True
Example 2
Input: can_install_all(3, [[0, 1], [1, 2], [2, 0]])
Output: False
Example 3
Input: can_install_all(1, [])
Output: True
Hints
Hint 1
Build a directed adjacency list from the dependency pairs, then think about what it means to traverse it depth-first.
Hint 2
During DFS, maintain two sets: nodes fully processed (done) and nodes on the current recursion stack (in-progress). A back edge — reaching an in-progress node — signals a cycle.
Hint 3
Iterate over every node as a potential DFS start so that disconnected components are all checked.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Intuition
Model the problem as a directed graph where each node is a package and each directed edge a → b means "a must be installed before b". A valid installation order exists if and only if this graph is a Directed Acyclic Graph (DAG) — i.e., it contains no cycle.
Algorithm: DFS with three-colour marking
Classic cycle detection on a directed graph uses a depth-first search where each node is in one of three states:
| State | Meaning |
|---|---|
0 (white) | Not yet visited |
1 (grey) | Currently on the DFS recursion stack |
2 (black) | Fully explored; all descendants are safe |
During DFS from a node:
- Mark it grey (in-progress).
- Recurse into each neighbour.
- If a neighbour is grey, we've found a back edge — a cycle exists.
- If a neighbour is black, it was already fully explored safely; skip it.
- Mark the node black when all its neighbours return safely.
We iterate over every node 0..n-1 as a possible DFS root so that disconnected components are all examined.
Why it is correct
- A back edge (grey → grey) is present if and only if the graph contains a directed cycle (standard DFS theorem for directed graphs).
- Duplicate edges are harmless: revisiting a black node terminates immediately.
- Self-loops
[a, a]produce an immediate back-edge hit since the node is grey when it reaches itself.
Complexity
- Time: O(n + E) where E = number of unique edges. Each node and edge is visited at most once.
- Space: O(n + E) for the adjacency list and the recursion stack (depth up to n in the worst case). Python's default recursion limit may need adjustment for very deep graphs, but for n ≤ 2000 it is fine.
from typing import List
def can_install_all(n: int, dependencies: List[List[int]]) -> bool:
# Build adjacency list (directed: a -> b means a before b)
adj = [[] for _ in range(n)]
for a, b in dependencies:
adj[a].append(b)
# 0 = unvisited, 1 = in current DFS stack, 2 = fully processed
state = [0] * n
def dfs(node: int) -> bool:
"""Return True if a cycle is found."""
if state[node] == 1:
return True # back edge -> cycle
if state[node] == 2:
return False # already fully explored, safe
state[node] = 1 # mark as in-progress
for neighbor in adj[node]:
if dfs(neighbor):
return True
state[node] = 2 # mark as done
return False
for start in range(n):
if state[start] == 0:
if dfs(start):
return False # cycle found
return True