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:
[0, 104].-105 <= Node.val <= 105pos is -1 or a valid index in the linked-list.Follow up: Can you solve it using O(1) (i.e. constant) memory?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are walking along a path made of stepping stones connected one after the other, and you want to know if the path eventually loops back on itself in a circle. The brute force strategy involves keeping a written record of every single stone you step on so you can check your past visits against your current location.
Here's how the algorithm would work step-by-step:
def has_cycle(head_node):
visited_stones_notepad = set()
current_stone = head_node
while current_stone is not None:
# Check notepad to detect a loop since revisiting a stone proves a cycle exists
if current_stone in visited_stones_notepad:
return True
# Record current stone location to ensure future visits can be identified
visited_stones_notepad.add(current_stone)
current_stone = current_stone.next
# Reaching the end of the path without repeats confirms the linked list is acyclic
return FalseTo find out if a path loops back on itself, the best strategy is to use two travelers moving at different speeds along the same path. If there is a loop, the faster traveler will eventually lap the slower one, much like runners on a circular track.
Here's how the algorithm would work step-by-step:
class Solution:
def hasCycle(self, head_node):
# Two pointers start at the head to traverse the list at different speeds.
slow_traveler = head_node
fast_traveler = head_node
while fast_traveler is not None and fast_traveler.next is not None:
# The fast pointer moves twice as fast to eventually lap the slow pointer if a cycle exists.
slow_traveler = slow_traveler.next
fast_traveler = fast_traveler.next.next
# Meeting point confirms a cycle because the faster pointer wrapped around.
if slow_traveler == fast_traveler:
return True
# Reaching the end of the list proves there is no cycle present.
return False| Case | How to Handle |
|---|---|
| Null head pointer representing an empty linked list | The algorithm checks if head is null or head.next is null at the start and immediately returns false. |
| Linked list with a single node and no cycle | The fast pointer will reach null on the first step, safely terminating the loop and returning false. |
| Single node pointing to itself forming a self-loop cycle | Both fast and slow pointers will occupy the same node after one iteration and match, correctly returning true. |
| Two-node list with a cycle pointing back to the head | The fast pointer will traverse the loop and meet the slow pointer within the first few steps. |
| Extremely large linked list without a cycle | The two-pointer approach runs in linear time and constant space, avoiding stack overflow and scaling efficiently. |
| A long linear tail followed by a very small cycle at the end | The fast pointer will eventually enter the cycle and lap the slow pointer, guaranteeing detection in O(N) time. |