THN Interview Prep

142. Linked List Cycle II

At a Glance

  • Topic: linked-list
  • Pattern: Fast & Slow Pointers (Floyd + entry)
  • Difficulty: Medium
  • Companies: Amazon, Google, Meta, Microsoft, Apple
  • Frequency: Very High
  • LeetCode: 142

Problem (one-liner)

If a singly linked list has a cycle, return the first node in the cycle; if no cycle, return nil.

Recognition Cues

  • Part two of 141: need the start of the loop, not just boolean
  • After slow and fast meet, move one pointer to head, advance both one step at a time until they meet at entry
  • Math: distance from head to entry equals distance from meet point to entry along the loop

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute forceO(n) space — set of seen nodes, first repeat is entry.
  • Better — not needed.
  • OptimalO(n) time / O(1) space — detect meet, then reset one pointer to head and walk in lockstep.

Optimal Solution

Go

type ListNode struct {
	Val  int
	Next *ListNode
}

func detectCycle(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}
	slow, fast := head, head
	for fast != nil && fast.Next != nil {
		slow = slow.Next
		fast = fast.Next.Next
		if slow == fast {
			slow = head
			for slow != fast {
				slow = slow.Next
				fast = fast.Next
			}
			return slow
		}
	}
	return nil
}

JavaScript

class ListNode {
	constructor(val = 0, next = null) {
		this.val = val;
		this.next = next;
	}
}

function detectCycle(head) {
	if (head === null) {
		return null;
	}
	let slow = head;
	let fast = head;
	while (fast !== null && fast.next !== null) {
		slow = slow.next;
		fast = fast.next.next;
		if (slow === fast) {
			slow = head;
			while (slow !== fast) {
				slow = slow.next;
				fast = fast.next;
			}
			return slow;
		}
	}
	return null;
}

Walkthrough

List 3 -> 2 -> 0 -> -4 with tail to index 1 (value 2).

phaseaction
meetslow and fast collide inside the loop
relinkset slow = head, move both one-by-one
entrythey meet at the node with value 2

Edge Cases

  • No cycle — first loop ends with fast nil.
  • Cycle is entire list — entry is head.
  • Self-loop on last node.

Pitfalls

  • Returning meet point from phase one — that is not the entry in general.
  • Reusing fast without keeping the meeting fast for second phase — you need the meeting node to walk with the head pointer; the code reuses fast from the meeting point (both travel at speed 1).

Similar Problems

Variants

  • Find length of loop — from entry, walk until you return to entry.
  • Unordered list with external ids — same math; store nothing extra if list nodes only.

Mind-Map Tags

#linked-list #floyd #cycle-entry #fast-slow

Last updated on

Spotted something unclear or wrong on this page?

On this page