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 ListNodeclass ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next
Example 1:
Output: true, there is a cycle between node 0 and node 3.
Example 2:
54320head
Output: false, there is no cycle in the linked list.
We recommend taking some time to solve the problem on your own before reading the solutions below.
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.
Solution
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
visited_nodes = set()
current_node = head
while current_node is not None:
if current_node in visited_nodes:
return True # Cycle detected
visited_nodes.add(current_node)
current_node = current_node.next
return False
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
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.
Visualization
Python
54320slowfast
initialize pointers
0 / 4
When the list contains a cycle, fast and slow eventually meet at 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.
Visualization
Python
54320slowfast
initialize pointers
0 / 3
If there is no cycle, eventually fast.next = None
When there is no cycle and the linked list has an even number of nodes, eventually fast = None (step 2 in the animation below).
Visualization
Python
5430slowfast
initialize pointers
0 / 3
Even # of nodes and no cycle, eventually fast.next = None
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
To construct the linked list that is used in the animation below, provide a list of integers nodes and an integer tail. Each integer in nodes is used as the value of a node in the linked list, and the order of the integers in the list will be the order of the nodes in the linked list.
The tail integer is the index of the node that the last node in the linked list points to form a cycle. If there is no cycle, set tail = -1.
Visualization
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
54320
linked list cycle
0 / 5
Edge Cases
Empty List
When the linked list is empty, fast = None to start, the while loop never runs and the function returns False.
Visualization
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
linked list cycle
0 / 2
nodes = [], tail = -1
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.
Visualization
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
1
linked list cycle
0 / 2
nodes = [1], tail = -1
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.
Visualization
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
1
linked list cycle
0 / 3
nodes = [1], tail = 0
Worst Case Scenario
In the worst case scenario, the fast pointer traverses the entire list twice before meeting the slow pointer.
Visualization
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
5432
linked list cycle
0 / 6
nodes = [5, 4, 3, 2], tail = 0
Test Your Knowledge
Login to take the complexity quiz and track your progress
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) We only use two pointers to do our traversal, which does not change with the number of nodes in the linked list.
Your account is free and you can post anonymously if you choose.