Java: Linked List Cycle

Thought Process

To detect a cycle in a linked list, we use the Floyd's Tortoise and Hare algorithm. This involves two pointers: a slow pointer that moves one step at a time and a fast pointer that moves two steps at a time. If there is a cycle, the fast pointer will eventually meet the slow pointer. If the fast pointer reaches the end of the list (NULL), it means there is no cycle.

/**
 * 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) {
        
        ListNode fast = head;
        ListNode slow = head;

        while(fast!=null && fast.next!=null){

            slow = slow.next;
            fast = fast.next.next;

            if(fast==slow)
                return true;
        }
        return false;
    }
}

Code Complexity

Time Complexity: O(n)

The algorithm iterates through the linked list once, making it linear in time complexity.

Space Complexity: O(1)

The algorithm uses only two pointers, ensuring constant space usage.

Code copied!