141. Linked List Cycle

Dare2Solve

Dare2Solve

141. Linked List Cycle
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

To detect a cycle in a linked list, we can use two pointers that traverse the list at different speeds. If there is a cycle, the faster-moving pointer will eventually meet the slower-moving pointer. This method leverages the concept of a "tortoise and hare" race, where the hare (fast pointer) moves two steps at a time and the tortoise (slow pointer) moves one step at a time.

Approach

  1. Initialization:

    • Check if the head is null or if the list contains only one node (head.next is null). In either case, return false because a cycle is not possible.
  2. Pointer Setup:

    • Initialize two pointers, slow and fast. Both start at the head of the list.
    • slow moves one step at a time.
    • fast moves two steps at a time.
  3. Traversal:

    • Iterate through the list:
      • In each iteration, move slow one step forward.
      • Move fast two steps forward.
      • If slow and fast meet at any point, return true because a cycle exists.
      • If fast or fast.next becomes null, return false because it indicates the end of the list and no cycle is present.
  4. Return:

    • If the loop exits, return false as no cycle was detected.

Complexity

Time Complexity:

Space Complexity:

Code

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) {
        if (!head || !head->next) {
            return false;
        }
        ListNode *slow = head;
        ListNode *fast = head->next;
        while (slow != fast) {
            if (!fast || !fast->next) {
                return false;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        return true;
    }
};

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:
        if not head or not head.next:
            return False
        slow = head
        fast = head.next
        while slow != fast:
            if not fast or not fast.next:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

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) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

JavaScript

var hasCycle = function(head) 
{
    if (!head || !head.next) {
        return false;
    }
    let slow = head;
    let fast = head.next;
    while (slow !== fast) {
        if (!fast || !fast.next) {
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
};