View on NeetCode
View on LeetCode

Problem

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 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) memory?

Solution

Approach 1: Floyd’s Cycle Detection (Tortoise and Hare)

The key insight is to use two pointers moving at different speeds. If there’s a cycle, the fast pointer will eventually catch up to the slow pointer.

Implementation

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head:
            return False

        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            if slow == fast:
                return True

        return False

Approach 2: Hash Set

Use a set to track visited nodes. If we see a node twice, there’s a cycle.

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        visited = set()
        current = head

        while current:
            if current in visited:
                return True
            visited.add(current)
            current = current.next

        return False

Complexity Analysis

Floyd’s Algorithm:

  • Time Complexity: O(n), where n is the number of nodes. In the worst case, fast pointer travels around the cycle once before meeting slow.
  • Space Complexity: O(1), we only use two pointers.

Hash Set:

  • Time Complexity: O(n), we visit each node once.
  • Space Complexity: O(n) for the hash set storing visited nodes.

Key Insights

  1. Two Speeds: The slow pointer moves one step at a time, the fast pointer moves two steps. If there’s a cycle, they must eventually meet.

  2. Why They Meet: In a cycle, the fast pointer enters the cycle first. Once both are in the cycle, the fast pointer gets one step closer to slow with each iteration. Eventually, the distance becomes zero.

  3. Loop Condition: We check fast and fast.next to ensure fast.next.next is safe to access. If fast reaches None, there’s no cycle.

  4. Meeting Point: They will meet inside the cycle, but not necessarily at the cycle’s start. The meeting point depends on the cycle’s length and where slow enters it.

  5. O(1) Space Achievement: Floyd’s algorithm uses only two pointers regardless of the list size, achieving the O(1) space requirement.