## Linked List Cycle

###### DESCRIPTION (credit Leetcode.com)

Write a function that takes in a parameter head of type ListNode that is a reference to the head of a linked list. The function should return True if the linked list contains a cycle, and False otherwise, without modifying the linked list in any way.

`# Definition of a ListNode class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next`

###### EXAMPLES

**Example 1**:

**Output**: true, there is a cycle between node 0 and node 3.

**Example 2**:

**Output**: false, there is no cycle in the linked list.

## Solutions

### 1. Keep Track of Visited Nodes

One approach to this problem is to keep a set of visited nodes while iterating through the linked list. At each node, we check if the node exists in the set. If it does, then the linked list contains a cycle. If it doesn't, we add the node to the set and move to the next node. If we reach the end of the linked list without encountering a node in the dictionary, then the linked list does not contain a cycle.

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):visited_nodes = set()current_node = headwhile current_node is not None:if current_node in visited_nodes:return True # Cycle detectedvisited_nodes.add(current_node)current_node = current_node.nextreturn False

**Time Complexity**: O(n), where n is the number of nodes in the linked list. In the worst case scenario, the algorithm visits each node once.
**Space Complexity**: O(n), where n is the number of nodes in the linked list. The space complexity is due to the set storing visited nodes.

### 2. Optimal Solution: Fast and Slow Pointers

The approach above requires O(n) space to store each visited node in the set. A more optimal solution solves this problem without using additional space (i.e. constant, O(1) space) by using **fast and slow pointers**.

This approach starts by initializing two pointers, fast and slow at the head of the list. It then iterates over the linked list, and in each iteration, the slow pointer advances by one node, while the fast pointer advances by two nodes.

#### Detecting a Cycle

If the linked list contains a cycle, **the fast pointer will eventually overlap the slow pointer, and both pointers will point to the same node.**

#### No Cycle

When there is no cycle, the fast pointer reaches the tail of the linked list, where fast.next = None (step 3 in the animation below). This is enough to determine the linked list does not contain a cycle.

When there is no cycle and the linked list has an even number of nodes, eventually fast = None (step 2 in the animation below).

Putting it all together, our algorithm involves the following steps:

- Initialize fast and slow pointers at the head of the linked list.
- Iterate over the linked list. Each iteration advances slow by one node and fast by two nodes.
- If the fast pointer reaches the end of the linked list (either fast.next = None or fast = None), then the linked list does not contain a cycle.
- If the fast and slow pointers meet at the same node (fast == slow), then the linked list contains a cycle.

## Code

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False

### Edge Cases

#### Empty List

When the linked list is empty, fast = None to start, the while loop never runs and the function returns False.

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False

#### Single Node (No Cycle)

When the linked list contains a single node without a cycle, fast.next = None to start and the function returns False without running the while loop.

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False

#### Single Node (with Cycle)

When the linked list contains a single node with a cycle, slow.next and fast.next.next point to the same single node, and the function returns True during the first iteration of the while loop.

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False

#### Worst Case Scenario

In the worst case scenario, the fast pointer traverses the entire list twice before meeting the slow pointer.

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False

## Complexity Analysis

**Time Complexity**: O(n), where n is the number of nodes in the linked list. In the worst case scenario, the fast pointer traverses the linked list twice, and the slow pointer traverses the linked list once, regardless of the number of nodes in the linked list.

**Space Complexity**: O(1), as we only use two pointers to traverse do our traversal, which does not change with the number of nodes in the linked list.

Loading comments...