Leetcode 141: Linked List Cycle

Detecting a cycle in a linked list using Floyd's Tortoise and Hare algorithm.

The original problem is here.

Hash Set approach

Algorithm

  1. Initialize an empty hash set to store visited nodes.
  2. Traverse the linked list starting from the head.
  3. For each node, check if it is already in the hash set.
    • If yes, a cycle is detected, return True.
    • If no, add the node to the hash set and move to the next node.
  4. If the end of the list is reached (None), no cycle exists, return False.

My solution

# 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:
        nodemap = {}
        node_now = head
        while node_now:
            if node_now in nodemap:
                return True
            nodemap[node_now] = True
            node_now = node_now.next
        return False

Complexity Analysis

Two Pointers approach

Algorithm

  1. Initialize slow and fast pointers synchronously at the head of the linked list.
  2. Loop exclusively while fast and fast.next are valid nodes (if either is None, the list possesses a finite tail and therefore cannot be cyclical).
  3. Step slow forward by one node (slow = slow.next).
  4. Step fast forward by two nodes (fast = fast.next.next).
  5. After updating, check if slow == fast. If they occupy the same node in memory, return True.
  6. If the while loop cleanly exhausts, return False.

My solution

# 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:
        slow = head
        fast = head
        
        # Traverse until the fast pointer exhausts the list length
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            # The hare caught up to the tortoise!
            if slow == fast:
                return True
                
        return False

Complexity Analysis

References