LeetCode 141: Linked List Cycle is an Easy linked list problem. This Python walkthrough develops a Floyd cycle detection solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Linked List |
| Reusable pattern | Floyd cycle detection |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.
For this problem specifically, advance one pointer by one node and another by two. They meet exactly when the reachable list contains a cycle. The invariant worth writing beside the code is: After k steps the fast pointer has moved twice as far as the slow pointer modulo any cycle.
Step-by-step algorithm
- Identify the input state consumed by
hasCycle(head)and initialize the data required by the Floyd cycle detection pattern. - Advance one pointer by one node and another by two. They meet exactly when the reachable list contains a cycle.
- After each update, verify the page’s central invariant: After k steps the fast pointer has moved twice as far as the slow pointer modulo any cycle.
- Finish only after the boundary behavior is covered: An empty list or one node without a self-loop has no cycle.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def hasCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseReading the implementation
The main entry point is hasCycle(head). The named working state includes slow, fast; those variables make the Floyd cycle detection state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, advance one pointer by one node and another by two. They meet exactly when the reachable list contains a cycle.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Advance one pointer by one node and another by two. They meet exactly when the reachable list contains a cycle. Each update records the current item without invalidating earlier decisions; consequently, after k steps the fast pointer has moved twice as far as the slow pointer modulo any cycle.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
tail.next=cycle.next; assert Solution().hasCycle(cycle); tail.next=NoneCommon mistakes and edge cases
- Problem-specific boundary: An empty list or one node without a self-loop has no cycle.
- Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
- Invariant check: after every update, confirm that after k steps the fast pointer has moved twice as far as the slow pointer modulo any cycle.
Interview review checklist
- Explain why Floyd cycle detection matches the structure of this input.
- State the invariant in one sentence before tracing code: After k steps the fast pointer has moved twice as far as the slow pointer modulo any cycle.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: An empty list or one node without a self-loop has no cycle.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 224. Basic Calculator · Next: 2. Add Two Numbers