← Back to DSA
#141
Linked List Cycle
Linked List Cycle solution for LeetCode 141, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Linked List Cycle
Why it belongs on this sheet
This introduces Floyd's cycle detection, which is one of the most reusable pointer tricks in interviews.
Pattern
Fast and slow pointers
Approach
Move one pointer one step at a time and the other two steps. If there is a cycle, they must eventually meet.
Java solution
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Complexity
- Time:
O(n) - Space:
O(1)
Interview note
Using a hash set works too, but Floyd is the stronger answer.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)