← Back to libraryQuestion 110 of 273
⌨️Java CodingIntermediate

Detect a Cycle in a Linked List

📌 Definition:

Determine whether a singly linked list contains a cycle (a node whose next points back to an earlier node).

📖 Detailed Explanation:

Floyd's cycle detection uses slow/fast pointers: if there is a cycle, the fast pointer eventually laps and meets the slow one; if fast reaches null, there is no cycle. O(n) time, O(1) space — no extra visited set needed.

💻 Solutions:
public static boolean hasCycle(Node head) {
    Node slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}
function hasCycle(head) {
  let slow = head, fast = head;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False
🔑 Key Points:
  • Floyd's slow/fast pointers
  • They meet inside a cycle; fast hits null otherwise
  • O(1) space vs a visited hash set
  • Extendable to find the cycle start
🌍 Real-World Example:

Cycle detection guards against infinite loops in linked structures, dependency graphs, and pointer-chasing algorithms.

🎯 Scenario-Based Interview Question:

A candidate stores visited nodes in a HashSet (O(n) space). What is the O(1)-space approach and why does it work?