LeetCode 141. Linked List Cycle

LeetCode 141. Linked List Cycle

    • [1. Problem Link 🔗](#1. Problem Link 🔗)
    • [2. Solution Overview 🧭](#2. Solution Overview 🧭)
    • [3. Solution 1: Floyd's Cycle Detection (Two Pointers) - Recommended](#3. Solution 1: Floyd's Cycle Detection (Two Pointers) - Recommended)
      • [3.1. Algorithm](#3.1. Algorithm)
      • [3.2. Important Points](#3.2. Important Points)
      • [3.3. Java Implementation](#3.3. Java Implementation)
      • [3.4. Time & Space Complexity](#3.4. Time & Space Complexity)
    • [4. Solution 2: Hash Set Approach](#4. Solution 2: Hash Set Approach)
      • [4.1. Algorithm思路](#4.1. Algorithm思路)
      • [4.2. Important Points](#4.2. Important Points)
      • [4.3. Java Implementation](#4.3. Java Implementation)
      • [4.4. Time & Space Complexity](#4.4. Time & Space Complexity)
    • [5. Solution 3: Node Marking (Destructive)](#5. Solution 3: Node Marking (Destructive))
      • [5.1. Algorithm思路](#5.1. Algorithm思路)
      • [5.2. Important Points](#5.2. Important Points)
      • [5.3. Java Implementation](#5.3. Java Implementation)
      • [5.4. Time & Space Complexity](#5.4. Time & Space Complexity)
    • [6. Solution 4: Recursive Approach](#6. Solution 4: Recursive Approach)
      • [6.1. Algorithm思路](#6.1. Algorithm思路)
      • [6.2. Important Points](#6.2. Important Points)
      • [6.3. Java Implementation](#6.3. Java Implementation)
      • [6.4. Time & Space Complexity](#6.4. Time & Space Complexity)
    • [7. Solution 5: Optimized Two Pointers with Different Starting Points](#7. Solution 5: Optimized Two Pointers with Different Starting Points)
      • [7.1. Algorithm思路](#7.1. Algorithm思路)
      • [7.2. Important Points](#7.2. Important Points)
      • [7.3. Java Implementation](#7.3. Java Implementation)
      • [7.4. Time & Space Complexity](#7.4. Time & Space Complexity)
    • [8. Solution Comparison 📊](#8. Solution Comparison 📊)
    • [9. Summary 📝](#9. Summary 📝)

LeetCode 141. Linked List Cycle

2. Solution Overview 🧭

Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.

Example:

复制代码
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list where the tail connects to the 1st node (0-indexed).

Constraints:

  • The number of nodes in the list is in the range [0, 10^4]
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked-list

Common approaches include:

  • Floyd's Cycle Detection (Two Pointers): Use slow and fast pointers
  • Hash Set: Store visited nodes in a hash set
  • Marking Nodes: Modify nodes to mark visited ones (destructive)

3.1. Algorithm

  • Use two pointers: slow moves one step at a time, fast moves two steps
  • If there's a cycle, the fast pointer will eventually meet the slow pointer
  • If there's no cycle, the fast pointer will reach the end (null)

3.2. Important Points

  • O(1) space complexity
  • Most efficient approach
  • Doesn't modify the original list

3.3. Java Implementation

java 复制代码
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast != null && fast.next != null) {
            slow = slow.next;          // Move slow pointer one step
            fast = fast.next.next;     // Move fast pointer two steps
            
            if (slow == fast) {        // Cycle detected
                return true;
            }
        }
        
        return false; // No cycle found
    }
}

3.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

4. Solution 2: Hash Set Approach

4.1. Algorithm思路

  • Traverse the linked list and store each visited node in a hash set
  • If we encounter a node that's already in the set, there's a cycle
  • If we reach the end (null), there's no cycle

4.2. Important Points

  • Simple and intuitive
  • Easy to understand and implement
  • Uses O(n) extra space

4.3. Java Implementation

java 复制代码
import java.util.HashSet;

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        HashSet<ListNode> visited = new HashSet<>();
        ListNode current = head;
        
        while (current != null) {
            if (visited.contains(current)) {
                return true; // Cycle detected
            }
            visited.add(current);
            current = current.next;
        }
        
        return false; // No cycle found
    }
}

4.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

5. Solution 3: Node Marking (Destructive)

5.1. Algorithm思路

  • Modify each visited node by setting a special marker (like setting value to a specific number)
  • If we encounter a node that's already marked, there's a cycle
  • This approach modifies the original list

5.2. Important Points

  • O(1) space complexity
  • Modifies the original list (not always acceptable)
  • Can cause issues if node values matter

5.3. Java Implementation

java 复制代码
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode current = head;
        // Use a special marker value
        int MARKER = Integer.MIN_VALUE;
        
        while (current != null) {
            if (current.val == MARKER) {
                return true; // Cycle detected
            }
            current.val = MARKER; // Mark the node
            current = current.next;
        }
        
        return false; // No cycle found
    }
}

5.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

6. Solution 4: Recursive Approach

6.1. Algorithm思路

  • Use recursion with a hash set to track visited nodes
  • At each step, check if current node has been visited
  • Recursively check the next node

6.2. Important Points

  • Demonstrates recursive thinking
  • Still uses O(n) space for recursion stack and hash set
  • Good for understanding recursion

6.3. Java Implementation

java 复制代码
import java.util.HashSet;

public class Solution {
    public boolean hasCycle(ListNode head) {
        return hasCycleHelper(head, new HashSet<>());
    }
    
    private boolean hasCycleHelper(ListNode node, HashSet<ListNode> visited) {
        if (node == null) {
            return false;
        }
        
        if (visited.contains(node)) {
            return true;
        }
        
        visited.add(node);
        return hasCycleHelper(node.next, visited);
    }
}

6.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

7. Solution 5: Optimized Two Pointers with Different Starting Points

7.1. Algorithm思路

  • Variation of Floyd's algorithm
  • Start slow and fast pointers from different positions
  • Can help avoid some edge cases

7.2. Important Points

  • Slight variation of the classic approach
  • Handles edge cases differently
  • Same time and space complexity

7.3. Java Implementation

java 复制代码
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head.next; // Start fast one step ahead
        
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false; // No cycle
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return true; // Cycle detected (slow == fast)
    }
}

7.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

8. Solution Comparison 📊

Solution Time Complexity Space Complexity Advantages Disadvantages
Floyd's Cycle Detection O(n) O(1) Most efficient, no extra space Mathematical proof needed
Hash Set O(n) O(n) Simple, intuitive Extra space usage
Node Marking O(n) O(1) No extra data structures Modifies original list
Recursive O(n) O(n) Demonstrates recursion Stack overflow risk
Optimized Two Pointers O(n) O(1) Handles edge cases well Slightly more complex

9. Summary 📝

  • Key Insight: Floyd's cycle detection algorithm is the optimal solution for cycle detection in linked lists
  • Recommended Approach: Solution 1 (Floyd's Cycle Detection) is the industry standard
  • Mathematical Proof: If there's a cycle, the fast pointer will eventually meet the slow pointer because the fast pointer catches up by 1 node per step
  • Pattern Recognition: This is a fundamental algorithm pattern used in many cycle detection problems

Why Floyd's Algorithm Works:

  • In each iteration, the distance between fast and slow pointers decreases by 1
  • Once the fast pointer enters the cycle, it will eventually catch up to the slow pointer
  • The time complexity is linear because the fast pointer traverses at most 2n nodes

For interviews, Floyd's cycle detection algorithm is expected as it demonstrates knowledge of optimal algorithms and space efficiency.

相关推荐
逸风尊者2 小时前
开发需掌握的知识:高精地图
人工智能·后端·算法
洛_尘2 小时前
数据结构--9:反射、枚举以及lambda表达式(了解即可)
java·开发语言·数据结构
资深web全栈开发2 小时前
力扣2536子矩阵元素加1-差分数组解法详解
算法·leetcode·矩阵·golang·差分数组
青衫码上行2 小时前
【Java Web学习 | 第12篇】JavaScript(6)DOM
java·开发语言·前端·javascript·学习
TDengine (老段)2 小时前
TDengine 字符串函数 POSITION 用户手册
android·java·大数据·数据库·物联网·时序数据库·tdengine
弘毅 失败的 mian2 小时前
C++、Java 还是测试开发?
java·c++·经验分享·笔记·测试开发·技术方向·就业
杜子不疼.2 小时前
【C++】 set/multiset底层原理与逻辑详解
java·开发语言·c++
q***31892 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
Macbethad3 小时前
如何用WPF做工控设置界面
java·开发语言·wpf