Identify Cycles in Linear Chains and Directed Networks
Trees & GraphsAuto-graded · 22 test casesLast updated
Detect structural loops in both a next-pointer chain using constant space and a directed graph reachable from a given entry point.
You are tasked with detecting loops across two different pointer-based structures: a linear sequence (singly linked list) and a directed graph.
Both structures are provided in array form:
-
Linear Chain:
linked_next: An array wherelinked_next[i]contains the zero-based index of the node following nodei. A value of-1indicates the end of the chain.linked_head: The starting node index of the sequence. Iflinked_headis-1, the sequence is empty.- A loop exists in the chain if following the
linked_nextindices starting fromlinked_headleads back to a previously visited node.
-
Directed Network:
graph: An adjacency list wheregraph[u]is a list of node indices reachable directly from nodeu.graph_start: The starting node index for exploration.- A loop exists in the network if there is a directed path reachable from
graph_startthat visits a node more than once (i.e., a reachable directed cycle).
Write a function that returns a list of two boolean values [has_linear_cycle, has_graph_cycle].
Constraints
0 <= len(linked_next) <= 10^5-1 <= linked_next[i] < len(linked_next)-1 <= linked_head < len(linked_next)0 <= len(graph) <= 10^5- Total edges across all lists in
graph<= 2 * 10^5 0 <= graph_start <= 10^5(Note:graph_startmay be greater than or equal tolen(graph)).- Nodes in
graph[u]are non-negative integers. If an edge references a node index>= len(graph), it should be treated as pointing to a node with no outgoing edges (or ignored safely upon out-of-bounds check).
Key Rules
- For the linear chain, cycle detection must strictly operate in $O(1)$ auxiliary memory (ignoring the input arrays).
- For the graph, only cycles reachable from
graph_startshould be reported asTrue. Unreachable cycles elsewhere in the graph should be ignored. - If
graph_startis outside the range[0, len(graph) - 1], no nodes are reachable, sohas_graph_cyclemust beFalse.
Examples
Example 1
Input: detect_cycles([1, 2, -1], 0, [[1], [2], []], 0)
Output: [False, False]
Example 2
Input: detect_cycles([1, 2, 0], 0, [[1], [2], [0]], 0)
Output: [True, True]
Example 3
Input: detect_cycles([-1], 0, [[1], [2], [1]], 0)
Output: [False, True]
Example 4
Input: detect_cycles([1, -1], 0, [[1], [], [3], [2]], 0)
Output: [False, False]
Hints
Hint 1
For the linear chain, consider using two pointers moving at different speeds (Floyd's Tortoise and Hare algorithm) to maintain O(1) auxiliary space.
Hint 2
For the graph, standard DFS with three node states (unvisited, active/visiting, completed) can detect back-edges efficiently.
Hint 3
To avoid stack overflow errors on large linear graphs, implement the graph traversal iteratively using an explicit stack.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires solving cycle detection for two distinct data structures:
1. Linear Chain (Linked List)
To achieve $O(1)$ auxiliary space complexity, we use Floyd's Cycle-Finding Algorithm (the Tortoise and Hare algorithm):
- Maintain two pointers,
slowandfast, starting atlinked_head. - In each step, move
slowforward by 1 link (linked_next[slow]) andfastforward by 2 links (linked_next[linked_next[fast]]). - If there is no cycle,
fast(or its next pointer) will eventually reach-1. - If a cycle exists,
fastwill enter the loop, loop around, and eventually meetslow.
2. Directed Network (Graph)
For directed graphs with multiple branches per node, Floyd's algorithm cannot be directly applied. Instead, we perform a Depth-First Search (DFS) starting from graph_start and track node states using three colors:
- 0 (WHITE / Unvisited): Node has not been visited yet.
- 1 (GRAY / Visiting): Node is currently on the recursion/traversal path.
- 2 (BLACK / Visited): Node and all its descendant paths have been fully explored without discovering cycles.
If during DFS we encounter an edge pointing to a node colored 1 (GRAY), a back-edge exists, confirming a cycle reachable from graph_start.
To handle large graph depths without encountering recursion stack limits in Python, we implement DFS iteratively using an explicit stack storing pairs of (node, child_index).
Complexity
-
Linear Chain:
- Time Complexity: $O(N)$ where $N$ is the number of nodes in
linked_next. - Space Complexity: $O(1)$ auxiliary memory.
- Time Complexity: $O(N)$ where $N$ is the number of nodes in
-
Directed Network:
- Time Complexity: $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges reachable from
graph_start. - Space Complexity: $O(V)$ auxiliary space for the color array and stack.
- Time Complexity: $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges reachable from
Solution Code
from typing import List
def detect_cycles(linked_next: List[int], linked_head: int, graph: List[List[int]], graph_start: int) -> List[bool]:
# Part 1: Linear chain loop detection (Floyd's Cycle Finding Algorithm)
slow = linked_head
fast = linked_head
has_linear_cycle = False
while fast != -1 and fast < len(linked_next) and linked_next[fast] != -1:
slow = linked_next[slow]
fast = linked_next[linked_next[fast]]
if slow == fast:
has_linear_cycle = True
break
# Part 2: Graph cycle detection using iterative 3-color DFS
# 0 = Unvisited, 1 = Visiting (Active on stack), 2 = Visited (Finished)
n = len(graph)
has_graph_cycle = False
if 0 <= graph_start < n:
color = [0] * n
# Stack entries keep track of (node, next_child_index_to_process)
stack = [(graph_start, 0)]
color[graph_start] = 1
while stack and not has_graph_cycle:
curr, child_idx = stack[-1]
if child_idx == len(graph[curr]):
color[curr] = 2
stack.pop()
else:
stack[-1] = (curr, child_idx + 1)
nbr = graph[curr][child_idx]
if 0 <= nbr < n:
if color[nbr] == 1:
has_graph_cycle = True
break
elif color[nbr] == 0:
color[nbr] = 1
stack.append((nbr, 0))
return [has_linear_cycle, has_graph_cycle]