← Home

142. Linked List Cycle II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
142

The trick here is to name the state correctly, then let the implementation follow. For 142. Linked List Cycle II, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 20 ms, faster than 22.46% of C++ online submissions for Linked List Cycle II.
02//Memory Usage: 11.2 MB, less than 16.67% of C++ online submissions for Linked List Cycle II.
03
04/**
05 * Definition for singly-linked list.
06 * struct ListNode {
07 *     int val;
08 *     ListNode *next;
09 *     ListNode(int x) : val(x), next(NULL) {}
10 * };
11 */
12class Solution {
13public:
14    ListNode *detectCycle(ListNode *head) {
15        set<ListNode*> visited;
16        ListNode* cur = head;
17        while(cur != NULL){
18            if(visited.find(cur) != visited.end()){
19                return cur;
20            }else{
21                visited.insert(cur);
22            }
23            cur = cur->next;
24        }
25        return NULL;
26    }
27};
28
29//https://leetcode.com/problems/linked-list-cycle-ii/discuss/44793/O(n)-solution-by-using-two-pointers-without-change-anything
30//Runtime: 12 ms, faster than 77.45% of C++ online submissions for Linked List Cycle II.
31//Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for Linked List Cycle II.
32/**
33 * Definition for singly-linked list.
34 * struct ListNode {
35 *     int val;
36 *     ListNode *next;
37 *     ListNode(int x) : val(x), next(NULL) {}
38 * };
39 */
40class Solution {
41public:
42    ListNode *detectCycle(ListNode *head) {
43        if(!head || !head->next) return NULL;
44        ListNode *slow = head, *fast = head;
45        bool isCycle = false;
46        
47        /*
48        slow : dist(slow) = dist(start to loop) + dist(loop to meet)
49        fast : dist(fast) = dist(start to loop) + dist(loop to meet) + dist(meet to loop) + dist(loop to meet)
50        because dist(slow)*2=dist(fast)
51        */
52        while(slow && fast){
53            slow = slow->next;
54            if(!fast->next) return NULL;
55            fast = fast->next->next;
56            if(slow == fast){
57                isCycle = true;
58                break;
59            }
60        }
61        
62        if(!isCycle){
63            return NULL;
64        }
65        
66        slow = head;
67        /*
68        now slow starts from head, and fast starts from meeting point
69        and we know that dist(start to loop) equals to dist(meeting to loop)
70        , so they will meet at loop
71        */
72        while(slow != fast){
73            slow = slow->next;
74            fast = fast->next;
75        }
76        
77        return slow;
78    }
79};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.