Algo-Sim › Linked Lists

Linked List Cycle

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Detect a cycle with Floyd's fast and slow pointers, in O(1) extra space.

Problem

Given the head of a linked list, return true if following next pointers ever revisits a node (the list has a cycle), and false if it reaches null. The pos input only describes where the tail links back; the code never sees it.

Constraints

Edge cases to test

Follow-up questions

Why must fast meet slow?
Inside the cycle the gap shrinks by one each step, so it reaches 0 within one lap.
Where does the cycle begin?
After they meet, move one pointer to the head and step both by one; they meet at the start (LC 142).
What is the hash set alternative?
Store visited nodes: O(n) time and O(n) space.

Solution

Java

public boolean hasCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
                return true;
        }
        return false;
    }
};

More Linked Lists problems