C++ 0142.cpp
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while (head)
{
if (seen.count(head) > 0)
return head;
seen.insert(head);
head = head->next;
}
return nullptr;
}
};
Difficulty
and has an acceptance rate of about 59% (3+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Linked List
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method detectCycle that determines whether a singly-linked list contains a cycle and, if so, returns the node where the cycle begins. The algorithm traverses the list while maintaining a collection of previously visited node pointers. When a node is encountered that already exists in this collection, the method concludes that a cycle is present and returns the repeated node as the entry point of the cycle. If the traversal reaches the end of the list without encountering a repeated node, the method returns nullptr, indicating the absence of a cycle.
Core Logic
The central mechanism relies on an unordered_set to store pointers to each node visited during the walk through the list. The loop continues as long as the current pointer head is not null. Inside the loop, the code checks whether the current node pointer is already present in the set. If the check succeeds, the current node is the first repeated node and is returned immediately. Otherwise, the node pointer is inserted into the set and the traversal proceeds to the next node.
unordered_set<ListNode*> seen;
while (head)
{
if (seen.count(head) > 0)
return head;
seen.insert(head);
head = head->next;
}
return nullptr;
The while (head) condition ensures that the loop terminates when the end of a non-cyclic list is reached. The seen.count(head) > 0 expression performs a constant-time lookup in the hash set to detect repetition. Insertion with seen.insert(head) also operates in average constant time, allowing the algorithm to maintain linear progress through the list.
Edge Cases
The implementation gracefully handles several boundary conditions without requiring explicit special-case code. When the input list is empty (head is nullptr), the loop condition fails immediately, and the method returns nullptr, correctly indicating that no cycle exists. For a list consisting of a single node that does not point to itself, the loop iterates once, inserts the sole node into the set, advances head to nullptr, and then exits, again returning nullptr. If the single node forms a self-referential cycle (its next pointer points to itself), the first iteration inserts the node, moves head to the same node, and the subsequent iteration detects the node already in the set, returning it as the cycle entry point.
When a longer list contains a cycle, the traversal proceeds through the acyclic prefix, inserting each node into the set. Upon reaching the first node that repeats (the start of the cycle), the membership test succeeds, and the method returns that node. This behavior correctly identifies the entry point of the cycle regardless of the length of the non-cyclic prefix or the size of the cycle.
Performance Considerations
The use of an unordered_set provides average-case constant-time operations for both membership testing and insertion. This choice eliminates the need for nested loops or repeated scanning of previously visited nodes, ensuring that each node is processed only once. The early return upon detection of a repeated node prevents unnecessary traversal of the remaining portion of the cycle, which can be beneficial when the cycle is large.
By storing raw node pointers rather than copying node contents, the implementation minimizes memory overhead per entry in the set. The algorithm also avoids recursion, thereby eliminating the risk of stack overflow for very long lists. The straightforward linear scan combined with hash-based bookkeeping yields an efficient solution for cycle detection in linked structures.
ELI5 - Simplified Explanation
Imagine you are walking along a path made of stepping stones. Each stone has a little arrow on it that points to the next stone you should step on. You want to see if this path ever loops back on itself like a circle.
To keep track of where you have been, carry a magical bucket that holds a memory of every stone you visit. As you step onto a new stone, first look inside your bucket to see if you have already held that stone before. If the stone is already in your bucket, you have found the start of a loop because you walked in a circle and arrived back at a place you visited earlier. If the stone is not in your bucket, drop a picture of it inside and follow the arrow to the next stone. Keep doing this over and over until you find a stone that you have already seen or until you reach the very end of the trail where no more stones exist.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | begeekmyfriend | C | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| begeekmyfriend | C | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 141: Linked List Cycle
Solved On The Same Day
- problem 263: Ugly Number
- problem 461: Hamming Distance
- problem 133: Clone Graph
- problem 143: Reorder List
- problem 264: Ugly Number II
- problem 313: Super Ugly Number
- problem 454: 4Sum II
- problem 477: Total Hamming Distance
- problem 10: Regular Expression Matching
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality