Coding Interview PatternsLinked List Cycle
EasyFast and Slow Pointers
Linked List Cycle
Explanation & Solution
Description
Given the head of a linked list, determine if the linked list has a cycle in it.
A cycle exists if some node in the list can be reached again by continuously following the next pointer. Internally, pos denotes the index of the node that the tail's next pointer connects to. Note that pos is not passed as a parameter — it is only used to build the linked list for testing.
Return true if there is a cycle in the linked list. Otherwise, return false.
Input:head = [3,2,0,-4], pos = 1
0
3
1
2
2
0
3
-4
Output: true
Explanation: There is a cycle where the tail node (-4) connects back to the node at index 1 (value 2).
Constraints
- The number of nodes in the list is in the range
[0, 10⁴] -10⁵ <= Node.val <= 10⁵posis-1or a valid index in the linked list
Approach
Fast and Slow Pointers pattern
1. Initialize Two Pointers
- Set
slowtohead - Set
fasttohead - Both pointers start at the beginning of the linked list
2. Traverse the List
- Loop while
fastis not null andfast.nextis not null - Move
slowforward by one step:slow = slow.next - Move
fastforward by two steps:fast = fast.next.next
3. Check for Cycle
- After each move, compare
slowandfast - If
slow === fast, the two pointers have met inside the cycle - Return
true— a cycle exists
4. No Cycle Found
- If the loop exits (i.e.,
fastorfast.nextisnull), the list has a definite end - Return
false— there is no cycle
Key Insight
- This is Floyd's Cycle Detection algorithm (tortoise and hare)
- If a cycle exists, the fast pointer will eventually "lap" the slow pointer and they will meet
- If no cycle exists, the fast pointer will reach the end of the list
Time
O(n)in the worst case, the fast pointer traverses the list twiceSpace
O(1)only two pointer variables are used, no extra data structures neededVisualization
Input:
Linked List Traversal
—
Press play to start traversal
Slow (S)Fast (F)Both
6 steps