KatInterview

141. Linked List Cycle

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if a given linked list has a cycle. A cycle exists if a node can be reached again by following the next pointers. The follow-up question, "Can you solve it using O(1) (i.e. constant) memory?", is a strong hint towards an algorithm that does not use extra data structures proportional to the list size, such as a hash set.

Solution

Linked List Cycle in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        # Initialize two pointers, slow and fast, to the head of the list.
        slow, fast = head, head

        # The loop continues as long as the fast pointer and its next node are not None.
        # This prevents an AttributeError when accessing fast.next.next.
        while fast and fast.next:
            # Move slow pointer one step.
            slow = slow.next
            # Move fast pointer two steps.
            fast = fast.next.next

            # If slow and fast pointers meet, a cycle is detected.
            if slow == fast:
                return True
        
        # If the loop finishes, the fast pointer reached the end of the list, so no cycle.
        return False

Linked List Cycle in Java

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        // Initialize two pointers, slow and fast, to the head of the list.
        ListNode slow = head;
        ListNode fast = head;

        // The loop continues as long as the fast pointer and its next node are not null.
        // This check prevents a NullPointerException when we access fast.next.next.
        while (fast != null && fast.next != null) {
            // Move the slow pointer one step forward.
            slow = slow.next;
            // Move the fast pointer two steps forward.
            fast = fast.next.next;

            // If the slow and fast pointers meet, it means there is a cycle.
            if (slow == fast) {
                return true;
            }
        }

        // If the loop completes, the fast pointer has reached the end of the list,
        // which means there is no cycle.
        return false;
    }
}

Linked List Cycle in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        // Initialize two pointers, slow and fast, to the head of the list.
        ListNode *slow = head;
        ListNode *fast = head;

        // The loop continues as long as fast pointer and its next node are not null.
        // This prevents null pointer exception when accessing fast->next->next.
        while (fast != nullptr && fast->next != nullptr) {
            // Move slow pointer one step.
            slow = slow->next;
            // Move fast pointer two steps.
            fast = fast->next->next;

            // If slow and fast pointers meet, a cycle is detected.
            if (slow == fast) {
                return true;
            }
        }

        // If the loop finishes, it means fast reached the end of the list, so no cycle.
        return false;
    }
};

Linked List Cycle in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    // Initialize two pointers, slow and fast, to the head of the list.
    let slow = head;
    let fast = head;

    // The loop continues as long as the fast pointer and its next node are not null.
    // This check prevents runtime errors when accessing fast.next.next.
    while (fast && fast.next) {
        // Move slow pointer one step. The non-null assertion `!` is safe because
        // if fast is not null, slow (which is behind fast) cannot be null either.
        slow = slow!.next;
        // Move fast pointer two steps.
        fast = fast.next.next;

        // If slow and fast pointers meet, a cycle is detected.
        if (slow === fast) {
            return true;
        }
    }

    // If the loop finishes, the fast pointer has reached the end of the list,
    // so no cycle exists.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.