← Home

141. Linked List Cycle

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

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 141. Linked List Cycle, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are hasCycle.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • 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. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

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), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 812 ms, faster than 9.19% of C++ online submissions for Linked List Cycle.
02//Memory Usage: 11.4 MB, less than 23.68% of C++ online submissions for Linked List Cycle.
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    bool hasCycle(ListNode *head) {
15        set<ListNode*> seen;
16        ListNode* cur = head;
17        
18        while(cur != NULL){
19            // cout << cur->val << " ";
20            if(find(seen.begin(), seen.end(), cur) == seen.end())
21                seen.insert(cur);
22            else
23                return true;
24            cur = cur->next;
25        }
26        cout <<endl;
27        
28        return false;
29    }
30};
31
32//Approach 2: Two Pointers
33//time: O(n), space: O(1)
34//Runtime: 8 ms, faster than 97.58% of C++ online submissions for Linked List Cycle.
35//Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Linked List Cycle.
36/**
37 * Definition for singly-linked list.
38 * struct ListNode {
39 *     int val;
40 *     ListNode *next;
41 *     ListNode(int x) : val(x), next(NULL) {}
42 * };
43 */
44class Solution {
45public:
46    bool hasCycle(ListNode *head) {
47        if(head == NULL || head->next == NULL) return false;
48        ListNode *slow = head, *fast = head->next;
49        //if there is a cycle, fast will eventually catch up slow
50        while(slow != fast){
51            if(fast == NULL || fast->next == NULL)
52                return false;
53            slow = slow->next;
54            fast = fast->next->next;
55        }
56        return true;
57    }
58};

Cost

Complexity

Time
O(n), space: O(1)
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.