Linked List
Linked List Cycle
easy
DESCRIPTION (inspired by 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
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.
Code Editor
Python
Run your code to see results here
Have suggestions or found something wrong?
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 = 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
What is the time complexity of this solution?
1
O(n)
2
O(N + Q)
3
O(m * n)
4
O(m * n * 4^L)
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
initialize pointers
0 / 4
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
initialize pointers
0 / 3
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
initialize pointers
0 / 3
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.
Try these examples:
Visualization
Python
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
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 = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False
linked list cycle
0 / 2
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 = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False
linked list cycle
0 / 2
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 = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False
linked list cycle
0 / 3
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 = valself.next = nextdef hasCycle(head):slow = headfast = headwhile fast and fast.next:slow = slow.nextfast = fast.next.nextif slow == fast:return Truereturn False
linked list cycle
0 / 6
What is the time complexity of this solution?
1
O(n)
2
O(N + Q)
3
O(m * n)
4
O(m * n * 4^L)
Mark as read