Linked List Cycle - Fast and Slow Pointers Pattern
Linked List Cycle in Java using the Fast and Slow Pointers pattern: problem statement, approach, template, complexity, and interview tips.
Linked List Cycle
Problem Statement
Determine whether a linked list contains a cycle.
Pattern: Fast and Slow Pointers
Advance two pointers at different speeds to detect cycles, find midpoints, or find repeated values without extra memory.
Use this pattern when you work with linked lists or sequences that may loop, or you need the middle of a list in one pass.
Approach
- Start both pointers at the head (or start value).
- Move slow one step and fast two steps each iteration.
- Interpret where they meet or where fast ends.
Pattern Template (Java)
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// if (slow == fast) a cycle exists
}
Adapt this template to the exact rules of Linked List Cycle: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n) time and O(1) space.
Interview Tips
- Check both fast and fast.next for null to avoid a NullPointerException.
- For cycle start, reset one pointer to the head after the first meeting.
- Start with a brute-force idea, state its complexity, then explain how the Fast and Slow Pointers pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Next: Happy Number
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.