Problem 142

Abstract / Summary

Find the node where a cycle begins in a linked list or determine that there is no cycle.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
14 lines | 325 bytes | submitted August 19, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (3+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Linked List
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.81 | σ = 1.27

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
55 links | 40 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 142 | Linked List Cycle II | Algorithm Explained (Java + Whiteboard)'
Xavier Elon 7 mins
LeetCode 142 | Linked List Cycle II | Algorithm Explained (Java + Whiteboard)
YouTube video 'Linked List Cycle 2 (LeetCode 142) | Full solution with mathematical proof | Study Algorithms'
Nikhil Lohia 19 mins
Linked List Cycle 2 (LeetCode 142) | Full solution with mathematical proof | Study Algorithms
YouTube video 'linked list cycle ii | Linked List Cycle II | leetcode 142 | twp pointer | list'
Naresh Gupta 7 mins
linked list cycle ii | Linked List Cycle II | leetcode 142 | twp pointer | list
YouTube video 'Linked List Cycle II | Live Coding with Explanation | Leetcode #142'
Algorithms Made Easy 6 mins
Linked List Cycle II | Live Coding with Explanation | Leetcode #142
YouTube video 'Linked List Cycle II | Leet code 142 | Theory explained + Python code'
Sai Anish Malla 12 mins
Linked List Cycle II | Leet code 142 | Theory explained + Python code
YouTube video 'Cycle Node In Linked List | Leetcode 142 Linked List Cycle II Solution'
Pepcoding 30 mins
Cycle Node In Linked List | Leetcode 142 Linked List Cycle II Solution
YouTube video 'Linked List Cycle II🔥 | Leetcode 142 | Linked List'
Ayushi Sharma 10 mins
Linked List Cycle II🔥 | Leetcode 142 | Linked List
YouTube video 'Linked List Cycle II | LeetCode 142 | Medium'
Code And Coffee 9 mins
Linked List Cycle II | LeetCode 142 | Medium
YouTube video 'Linked List Cycle II - Linked List - Leetcode 142'
Aryan Mittal 20 mins
Linked List Cycle II - Linked List - Leetcode 142
YouTube video 'Linked List Cycle II - Leetcode 142 - Python'
TechError 5 mins
Linked List Cycle II - Leetcode 142 - Python
YouTube video 'Linked List Cycle II | Leetcode 142 | Medium Level'
Technosage 9 mins
Linked List Cycle II | Leetcode 142 | Medium Level
YouTube video 'LeetCode Problem: 142. Linked List Cycle II | Java Solution'
Code for Interview 13 mins
LeetCode Problem: 142. Linked List Cycle II | Java Solution
YouTube video 'Cycle detection in Linked List || 141. Linked List Cycle || 142. Linked List Cycle II || Interview'
code Explainer 12 mins
Cycle detection in Linked List || 141. Linked List Cycle || 142. Linked List Cycle II || Interview
YouTube video 'Daily Leetcode #1073: Mar 09, 2023 - 142. Linked List Cycle II'
Programming Live with Larry 17 mins
Daily Leetcode #1073: Mar 09, 2023 - 142. Linked List Cycle II
YouTube video 'Linked List Cycle II  | Leetcode 142 | Live coding session 🔥🔥🔥🔥 | Fast  Slow Pointer With Proof'
Coding Decoded 8 mins
Linked List Cycle II | Leetcode 142 | Live coding session 🔥🔥🔥🔥 | Fast Slow Pointer With Proof
YouTube video '142. Linked List Cycle II | JavaScript | Two Pointers | Floyd's Algorithm | LeetCode Daily Challenge'
LeetCodeWithMonu 13 mins
142. Linked List Cycle II | JavaScript | Two Pointers | Floyd's Algorithm | LeetCode Daily Challenge
YouTube video 'Linked List Cycle II Explained in Telugu | Leetcode 142 | Python Brute Force & Optimal | srkcodes'
Srk Codes 13 mins
Linked List Cycle II Explained in Telugu | Leetcode 142 | Python Brute Force & Optimal | srkcodes
YouTube video 'Linked List Cycle II | Leetcode | Programming in Tamil | Coding in Tamil | Coding | C++ | DSA'
Adi Explains 10 mins
Linked List Cycle II | Leetcode | Programming in Tamil | Coding in Tamil | Coding | C++ | DSA
YouTube video '142 || Linked List Cycle II || C++ || Leetcode Daily Challenge'
CodeFreaks 11 mins
142 || Linked List Cycle II || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #659: Jan 19, 2022 - 142. Linked List Cycle II'
Programming Live with Larry 33 mins
Daily Leetcode #659: Jan 19, 2022 - 142. Linked List Cycle II
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 6 medium 1 hard
10 solutions   August 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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