LeetCode 141. Linked List Cycle

Post by ailswan Oct.12, 2023

141. Linked List Cycle

Problem Statement

link: https://leetcode.com/problems/linked-list-cycle/ https://leetcode.cn/problems/linked-list-cycle/

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example:

Input: head = [3,2,0,-4], pos = 1 Output: true

Input: head = [1,2], pos = 0 Output: true

Input: head = [1], pos = -1 Output: false

Solution Approach

To detect a cycle in a linked list, employ the Floyd’s cycle-finding algorithm using two pointers moving at different speeds.

Algorithm

  1. Initialization: Use two pointers, one moving fast (two steps at a time) and the other moving slow (one step at a time).
  2. Traversal: Traverse the linked list with both pointers. If there’s a cycle, the fast pointer will eventually catch up to the slow pointer.
  3. Cycle Detection: The presence of a cycle is confirmed when the slow pointer equals the fast pointer during traversal. If the fast pointer reaches the end of the list, then there’s no cycle.

Implement

    class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow == fast:
                return True
        return False