Linked List Cycle
LeetCode 141 · Easy · solution, intuition & step-by-step walkthrough
Floyd: fast meets slow ⇔ cycle.
This is how I solved Linked List Cycle (LeetCode 141), an easy problem from the Fast & Slow Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.
Approach
- 1
slow and fast start at head.
- 2
Advance slow by 1 and fast by 2.
- 3
Equal → cycle; fast hits None → no cycle.
How I solved it
Floyd's cycle detectionPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while fast and fast.next!=None:
slow = slow.next
fast = fast.next.next
if slow==fast:
return True
return FalseLinked List Cycle — FAQ
What is the intuition behind Linked List Cycle?
Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.
How do you solve Linked List Cycle (LeetCode 141)?
1. slow and fast start at head. 2. Advance slow by 1 and fast by 2. 3. Equal → cycle; fast hits None → no cycle.
What is the time and space complexity of Linked List Cycle?
Time: O(n). Space: O(1). (Accepted approach: Floyd's cycle detection.)
What are common mistakes in Linked List Cycle?
Compare nodes (identity), not values.