AlgoTales · Roadmap

Detecting cycles

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Detecting a cycle means finding out whether following links from item to item ever leads back to somewhere you have already been. The simple method is to remember every place visited. If you step onto a visited place, you are going in circles and must stop.

Practical use cases

  • Web app: Catching an endless redirect chain. A site migration sets up hundreds of redirect rules, and page A accidentally sends to B, which sends back to A. Browsers show "too many redirects". A checker script follows each rule while keeping a set of visited URLs, and the moment it meets one twice, it reports the loop with the exact pages involved.
  • Web app: Circular category or comment parents. An admin sets a category's parent to one of its own children by mistake, and the menu page then loops forever or crashes. Before saving, the code follows the parent links up from the chosen parent while remembering what it saw. If it returns to the category being edited, the save is refused with a clear message.
  • System: Dependency checks and garbage collectors. Package managers must refuse a library that depends on itself through other libraries. Language runtimes also must notice objects that point to each other in a ring so their memory can be reclaimed. Both rely on marking visited items and stopping on a repeat.

The story: Lost in the Mohalla Lanes

Mira's new friend Zoya moved to an old mohalla where narrow lanes twist and join in odd ways. Zoya set out to find the post office, following her own rule: "At each junction, take the lane on my right." She walked a long time, and the shops started looking familiar. The same sweet shop again! She was walking in a circle.

Mira, watching on the phone, said, "Carry a piece of chalk! At each junction mark a small cross. If you reach a junction that already has a cross, you know you are going in circles. If you reach the end of the lane (the main road), you are not."

Zoya followed the plan. Cross, cross, cross, cross... and then at junction 3 she saw a cross she had made earlier. "Loop!" she shouted, and finally asked for directions instead of following the lane blindly.

That is cycle detection in a linked list using memory: remember every node you have visited in a set; if the next node is already in the set, there is a cycle; if you reach null, there is none. It is simple and always correct, but it needs extra space for the set. In the next lesson Floyd will show a way with no chalk at all.

How to spot this problem, and where you need it

A process follows links from one thing to the next and sometimes never finishes, hangs the page or fills memory, because the links lead back to something already visited.

Signs you need it

  • A page, script or queue job hangs or times out only for certain data, and the data contains parent, next or redirect pointers.
  • Users can edit relationships such as manager, parent category, reply-to or depends-on, so a loop can be created by accident.
  • The problem statement says "does the list loop?", "is there a cycle?" or "will this ever end?".

Where to use it in a project

  • Validating redirect rules, URL rewrite tables and short-link chains before deploying them.
  • Saving hierarchies such as categories, org charts and nested comments without creating loops.
  • Checking task or package dependency chains before running them.

The solution

Walk along the links one at a time, and put every item you reach into a set of visited items. Before stepping onto an item, ask the set whether you have seen it. If yes, there is a cycle and you can report where. If you reach the end with no link left, there is no cycle. It needs extra memory for the set but is very simple and reliable.

Payoff: Before: a page that hung until the server timed out after 30 seconds. After: the loop is reported in a fraction of a second with the offending items named.

Explain it like I am 8

You are walking through rooms and each room has an arrow to the next. To know if you are going in circles, put a sticker in every room you enter. If you ever walk into a room that already has a sticker, you are in a circle.

How it works, step by step

  1. Create an empty set of visited nodes.
  2. Start at the head. Look at the current node.
  3. If the node is already in the set, you have found a cycle. Stop and say yes.
  4. Otherwise add the node to the set and move to cur.next.
  5. If you reach null the list ends normally. Say no cycle.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val) { $this->val = $val; }
}

function hasCycle(?Node $head): bool {
    $seen = [];                               // the chalk list: node ids we have visited
    for ($cur = $head; $cur !== null; $cur = $cur->next) {
        $id = spl_object_id($cur);            // a unique id for each node object
        if (isset($seen[$id])) return true;   // chalk mark found: we are going round in circles
        $seen[$id] = true;
    }
    return false;                             // reached null: a normal list
}

// build 1 -> 2 -> 3 -> 4 -> 5 -> 6
$nodes = [];
for ($i = 1; $i <= 6; $i++) { $nodes[$i] = new Node($i); }
for ($i = 1; $i < 6; $i++) { $nodes[$i]->next = $nodes[$i + 1]; }

echo 'Straight list: ' . (hasCycle($nodes[1]) ? 'cycle' : 'no cycle') . "\n";   // no cycle
$nodes[6]->next = $nodes[3];                                                      // 6 points back to 3
echo 'After 6 -> 3 : ' . (hasCycle($nodes[1]) ? 'cycle' : 'no cycle') . "\n";   // cycle

JavaScript

class Node {
  constructor(val) { this.val = val; this.next = null; }
}

function hasCycle(head) {
  const seen = new Set();                 // the chalk list: nodes we have visited
  for (let cur = head; cur !== null; cur = cur.next) {
    if (seen.has(cur)) return true;       // chalk mark found: we are going round in circles
    seen.add(cur);
  }
  return false;                           // reached null: a normal list
}

// build 1 -> 2 -> 3 -> 4 -> 5 -> 6
const nodes = [];
for (let i = 1; i <= 6; i++) nodes[i] = new Node(i);
for (let i = 1; i < 6; i++) nodes[i].next = nodes[i + 1];

console.log('Straight list: ' + (hasCycle(nodes[1]) ? 'cycle' : 'no cycle'));   // no cycle
nodes[6].next = nodes[3];                                                        // 6 points back to 3
console.log('After 6 -> 3 : ' + (hasCycle(nodes[1]) ? 'cycle' : 'no cycle'));   // cycle

Java

import java.util.*;

public class Main {
    static class Node {
        int val;
        Node next = null;
        Node(int val) { this.val = val; }
    }

    static boolean hasCycle(Node head) {
        Set<Node> seen = new HashSet<>();         // the chalk list: nodes we have visited
        for (Node cur = head; cur != null; cur = cur.next) {
            if (seen.contains(cur)) return true;  // chalk mark found: we are going round in circles
            seen.add(cur);
        }
        return false;                             // reached null: a normal list
    }

    public static void main(String[] args) {
        // build 1 -> 2 -> 3 -> 4 -> 5 -> 6
        Node[] nodes = new Node[7];
        for (int i = 1; i <= 6; i++) nodes[i] = new Node(i);
        for (int i = 1; i < 6; i++) nodes[i].next = nodes[i + 1];

        System.out.println("Straight list: " + (hasCycle(nodes[1]) ? "cycle" : "no cycle"));   // no cycle
        nodes[6].next = nodes[3];                                                               // 6 points back to 3
        System.out.println("After 6 -> 3 : " + (hasCycle(nodes[1]) ? "cycle" : "no cycle"));   // cycle
    }
}

Go

package main

import "fmt"

type Node struct {
	val  int
	next *Node
}

func hasCycle(head *Node) bool {
	seen := map[*Node]bool{} // the chalk list: nodes we have visited
	for cur := head; cur != nil; cur = cur.next {
		if seen[cur] {
			return true // chalk mark found: we are going round in circles
		}
		seen[cur] = true
	}
	return false // reached nil: a normal list
}

func describe(head *Node) string {
	if hasCycle(head) {
		return "cycle"
	}
	return "no cycle"
}

func main() {
	// build 1 -> 2 -> 3 -> 4 -> 5 -> 6
	nodes := make([]*Node, 7)
	for i := 1; i <= 6; i++ {
		nodes[i] = &Node{val: i}
	}
	for i := 1; i < 6; i++ {
		nodes[i].next = nodes[i+1]
	}

	fmt.Println("Straight list:", describe(nodes[1])) // no cycle
	nodes[6].next = nodes[3]                          // 6 points back to 3
	fmt.Println("After 6 -> 3 :", describe(nodes[1])) // cycle
}

Time: O(n) · Extra space: O(n). Each node is looked at once, but the set of visited nodes can grow as large as the list.

Watch out for

  • Comparing node values instead of node identity: two different nodes can hold the same value without being a cycle.
  • Looping with while (cur !== null) but never recording visited nodes. On a cyclic list that runs forever.
  • Forgetting the empty list: head can be null and should just return false.

Quick check

  1. You reach a node that is already in your visited set. What does that mean?
    • The list has a cycle
    • The list is sorted
    • The list is empty
    • The list has duplicates
  2. What do you check in the visited set?
    • The node's value
    • The node itself (its identity)
    • The node's position in memory only for sorted lists
    • The length
  3. Space used by the visited-set method?
    • O(1)
    • O(log n)
    • O(n)
    • O(n²)