AlgoTales · Roadmap

Removing cycles

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Removing a cycle means first detecting it, then finding the exact item where the loop begins, and finally cutting the link that points back. The result is a normal chain with a clean end, and no data is lost.

Practical use cases

  • Web app: Repairing a corrupted next-job chain. A queue table links each job to the next, and a bug made the last job point back to the third. Instead of deleting everything, a repair script finds where the loop starts and sets the last job's next link to empty. The queue then runs through once and finishes, with no job lost.
  • Web app: Fixing a broken menu hierarchy. A CMS menu got a child item pointing at one of its own ancestors after an import, and the site header stopped rendering. The admin tool finds the item where the loop begins and offers to detach just that one link, so the rest of the menu stays untouched.
  • System: Defensive programming in data loaders. Libraries that load linked data from disk or the network cannot trust what they receive. A good loader checks for loops and repairs or rejects them instead of hanging, which keeps a single bad record from freezing the whole application.

The story: The Garland That Never Ended

Before Diwali, Grandpa Bhaskar was making a long marigold garland for the front door. By mistake, he tied the last flower back onto a flower in the middle. Instead of a straight garland it became a "6" shape: a straight stem leading into a loop. Mira picked up one end and walked along it, and walked, and walked, and never reached the end.

"We must cut it where it was wrongly tied," said Grandpa. "But where? First find that we are in a loop. Then find the place where the loop begins. Then cut the thread just before that place."

Mira used the tortoise and hare to prove there was a loop; they met at one flower inside it. Then the surprise trick: leave one walker at the meeting flower, send the other back to the start of the garland, and let both walk one flower at a time. They meet exactly at the flower where the loop begins. Mira could not believe it, but it always works.

Last, Mira walked once around from the loop start until she found the flower whose next was the loop start. Snip! She set that flower's thread to nothing (null). Now the garland was straight again and fit perfectly on the door. This three-part recipe (detect, find the start, cut the last link) is removing a cycle from a linked list.

How to spot this problem, and where you need it

You found out that a chain loops and now need to fix it, not just report it: locate where the loop starts and cut it so the chain ends normally.

Signs you need it

  • A follow-up in the problem says "return the node where the cycle begins" or "remove the cycle".
  • A chain in your database or memory has a link that points back to an earlier item and breaks any code that walks to the end.
  • You want to repair bad data automatically instead of failing the whole job.

Where to use it in a project

  • Repair scripts for linked rows such as job queues, menus and threaded comments.
  • Data importers that must clean untrusted chains before using them.
  • Admin tools that offer a one-click "fix the loop" action.

The solution

First run the slow and fast walkers until they meet inside the loop. Then put one walker back at the head and keep the other at the meeting point; move both one step at a time. They meet exactly at the item where the loop begins. Walk around once more to the item just before it and set that item's next link to empty. The chain now ends properly.

Payoff: Before: a chain that never ends and blocks the whole queue. After: one link cut, all items kept, and the run completes.

Explain it like I am 8

A necklace string got tied back to itself in the middle. First find that you are going round in circles. Then find the knot where the circle starts. Then snip the thread that goes back into the knot, and the string is straight again.

How it works, step by step

  1. Detect: run slow and fast from the head. If fast hits null, there is no cycle: do nothing.
  2. When they meet, move one pointer back to the head; keep the other at the meeting node.
  3. Move both one step at a time. When they become equal, that node is the start of the cycle.
  4. Walk from the cycle start until you reach the node whose next is the cycle start. This is the last node of the loop.
  5. Set that node's next to null. The list is now a normal list.

The code in four languages

PHP

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

// returns true if a cycle existed (and has now been removed)
function removeCycle(?Node $head): bool {
    $slow = $head;
    $fast = $head;
    while ($fast !== null && $fast->next !== null) {   // 1) detect with tortoise and hare
        $slow = $slow->next;
        $fast = $fast->next->next;
        if ($slow === $fast) break;
    }
    if ($fast === null || $fast->next === null) return false;   // no cycle

    $a = $head;                          // 2) find the start of the loop
    $b = $slow;                          //    (b waits at the meeting point)
    while ($a !== $b) { $a = $a->next; $b = $b->next; }
    $start = $a;

    $last = $start;                      // 3) find the node that points back to start
    while ($last->next !== $start) { $last = $last->next; }
    $last->next = null;                  //    and cut it
    return true;
}

$nodes = [];
for ($i = 1; $i <= 6; $i++) { $nodes[$i] = new Node($i); }
for ($i = 1; $i < 6; $i++) { $nodes[$i]->next = $nodes[$i + 1]; }
$nodes[6]->next = $nodes[3];             // the accidental knot: 6 -> 3

echo 'Cycle removed? ' . (removeCycle($nodes[1]) ? 'yes' : 'no') . "\n";
$out = [];
for ($c = $nodes[1]; $c !== null; $c = $c->next) { $out[] = $c->val; }
echo implode(' -> ', $out) . " -> null\n";                         // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
echo 'Second run, cycle removed? ' . (removeCycle($nodes[1]) ? 'yes' : 'no') . "\n";   // no

JavaScript

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

// returns true if a cycle existed (and has now been removed)
function removeCycle(head) {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {   // 1) detect with tortoise and hare
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) break;
  }
  if (fast === null || fast.next === null) return false;   // no cycle

  let a = head;                        // 2) find the start of the loop
  let b = slow;                        //    (b waits at the meeting point)
  while (a !== b) { a = a.next; b = b.next; }
  const start = a;

  let last = start;                    // 3) find the node that points back to start
  while (last.next !== start) last = last.next;
  last.next = null;                    //    and cut it
  return true;
}

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];
nodes[6].next = nodes[3];              // the accidental knot: 6 -> 3

console.log('Cycle removed? ' + (removeCycle(nodes[1]) ? 'yes' : 'no'));
const out = [];
for (let c = nodes[1]; c !== null; c = c.next) out.push(c.val);
console.log(out.join(' -> ') + ' -> null');                        // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
console.log('Second run, cycle removed? ' + (removeCycle(nodes[1]) ? 'yes' : 'no'));   // no

Java

import java.util.*;

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

    // returns true if a cycle existed (and has now been removed)
    static boolean removeCycle(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {   // 1) detect with tortoise and hare
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) break;
        }
        if (fast == null || fast.next == null) return false;   // no cycle

        Node a = head;                       // 2) find the start of the loop
        Node b = slow;                       //    (b waits at the meeting point)
        while (a != b) { a = a.next; b = b.next; }
        Node start = a;

        Node last = start;                   // 3) find the node that points back to start
        while (last.next != start) last = last.next;
        last.next = null;                    //    and cut it
        return true;
    }

    public static void main(String[] args) {
        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];
        nodes[6].next = nodes[3];            // the accidental knot: 6 -> 3

        System.out.println("Cycle removed? " + (removeCycle(nodes[1]) ? "yes" : "no"));
        List<String> out = new ArrayList<>();
        for (Node c = nodes[1]; c != null; c = c.next) out.add(String.valueOf(c.val));
        System.out.println(String.join(" -> ", out) + " -> null");   // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
        System.out.println("Second run, cycle removed? " + (removeCycle(nodes[1]) ? "yes" : "no"));   // no
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type Node struct {
	val  int
	next *Node
}

// removeCycle returns true if a cycle existed (and has now been removed).
func removeCycle(head *Node) bool {
	slow, fast := head, head
	for fast != nil && fast.next != nil { // 1) detect with tortoise and hare
		slow = slow.next
		fast = fast.next.next
		if slow == fast {
			break
		}
	}
	if fast == nil || fast.next == nil { // no cycle
		return false
	}

	a, b := head, slow // 2) find the start of the loop (b waits at the meeting point)
	for a != b {
		a = a.next
		b = b.next
	}
	start := a

	last := start // 3) find the node that points back to start
	for last.next != start {
		last = last.next
	}
	last.next = nil // and cut it
	return true
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	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]
	}
	nodes[6].next = nodes[3] // the accidental knot: 6 -> 3

	fmt.Println("Cycle removed?", yesNo(removeCycle(nodes[1])))
	var out []string
	for c := nodes[1]; c != nil; c = c.next {
		out = append(out, fmt.Sprint(c.val))
	}
	fmt.Println(strings.Join(out, " -> ") + " -> null")                     // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
	fmt.Println("Second run, cycle removed?", yesNo(removeCycle(nodes[1]))) // no
}

Time: O(n) · Extra space: O(1). Three short walks, each at most the size of the list, using only a few pointers.

Watch out for

  • Setting start.next = null instead of cutting the node before the start: that would remove the wrong link and chop off the rest of the loop.
  • Not handling "no cycle": check that fast reached null before doing the second phase.
  • Moving the second walker by two steps in the "find the start" phase. Both must move one step.

Quick check

  1. After the tortoise and hare meet, what do you do next to find the loop start?
    • Move both forward by two
    • Put one walker at the head and move both one step at a time
    • Reverse the list
    • Count the nodes in the loop and divide
  2. Which node's next do you set to null?
    • The head
    • The loop start
    • The meeting node, always
    • The last node of the loop, whose next is the loop start
  3. What if the list has no cycle?
    • Report false and change nothing
    • Cut the last node anyway
    • Reverse the list
    • Delete the head