Does This One-Way Network Contain a Loop?
Trees & GraphsAuto-graded · 22 test casesLast updated
Decide whether a directed graph given as an adjacency list contains a cycle, handling self-loops, parallel edges, disconnected parts and an empty graph.
Does This One-Way Network Contain a Loop?
You are given a network of one-way links between nodes. The network is stored as an adjacency list called adj. Nodes are numbered 0 to n - 1, where n = len(adj), and adj[u] lists every node v that has a one-way link u -> v.
Return True if you can start at some node, follow links, and come back to the node you started from (a directed cycle). Return False otherwise.
Rules and edge cases
- The graph may be disconnected. A cycle in any part of it counts.
- A self-loop (
uappears inadj[u]) is a cycle. - The same link may be listed more than once in
adj[u]. Repeated links alone do not form a cycle; only a genuine route that returns to its start does. - Two links in opposite directions between the same pair of nodes (
u -> vandv -> u) form a cycle. - Nodes reachable by several different routes do not by themselves imply a cycle. Only a route that returns to its start does.
- If
adjis empty (no nodes), returnFalse.
Input
adj: a list of lists of integers.adj[u]holds the targets of the links leaving nodeu. Every value is a valid node index in[0, n - 1].
Output
- A boolean:
Trueif the graph contains a directed cycle, otherwiseFalse.
Constraints
0 <= n <= 10^50 <= m <= 2 * 10^5, wheremis the total number of entries across all lists0 <= adj[u][i] < n- Aim for
O(n + m)time.
Examples
Example 1
Input: contains_cycle([[1], [2], [0]])
Output: True
Example 2
Input: contains_cycle([[1], [2], []])
Output: False
Example 3
Input: contains_cycle([[1, 2], [2], []])
Output: False
Example 4
Input: contains_cycle([[], [0], []])
Output: False
Hints
Hint 1
A visited set is not enough for directed graphs: a node can be reached by two different routes without any cycle. You need to tell apart 'on my current path' from 'seen earlier'.
Hint 2
Try repeatedly removing nodes that have no incoming links. What does it mean if some nodes can never be removed?
Hint 3
Count incoming links per node (counting repeats separately), start from nodes with count 0, and decrement counts of targets as you remove nodes. Compare how many nodes were removed to n.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use Kahn's topological-sort idea. A directed graph has a valid topological ordering exactly when it has no cycle.
- Compute the in-degree of every node. Each entry in an adjacency list counts, so repeated links are counted separately.
- Put every node with in-degree 0 into a queue. Nothing points to these nodes, so they can safely come first.
- Pop a node, count it as removed, and decrement the in-degree of each of its targets. Any target that reaches 0 joins the queue.
- When the queue is empty, a cycle exists if and only if fewer than
nnodes were removed.
Why it is correct
- Cycle present: every node on the cycle has an incoming link from its predecessor on the cycle. That predecessor can only be removed after the node itself is removed, which is circular, so none of the cycle's nodes is ever removed and the count stays below
n. - No cycle: every non-empty acyclic graph has a node with in-degree 0. Removing it leaves a smaller acyclic graph, so by induction every node is eventually removed and the count equals
n.
Edge cases follow naturally. An empty graph gives 0 == 0, so False. A self-loop gives its node an in-degree that can only drop once that node is removed, so it is never removed. Parallel links are added to the in-degree and subtracted again consistently. Disconnected parts are covered because all zero-in-degree nodes seed the queue.
An alternative is DFS with three colors (unvisited, on the current path, finished); reaching a node that is on the current path signals a cycle. Use an explicit stack to avoid recursion limits.
Complexity
- Time:
O(n + m), since each node and each link is handled a constant number of times. - Space:
O(n)for the in-degree array and the queue.
Reference solution
from collections import deque
from typing import List
def contains_cycle(adj: List[List[int]]) -> bool:
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(i for i in range(n) if indegree[i] == 0)
removed = 0
while queue:
u = queue.popleft()
removed += 1
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return removed != n