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.

相关推荐
nbsaas-boot8 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er8 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
leo__5208 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab
忆锦紫9 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
玄〤9 小时前
黑马点评中 VoucherOrderServiceImpl 实现类中的一人一单实现解析(单机部署)
java·数据库·redis·笔记·后端·mybatis·springboot
t198751289 小时前
基于自适应Chirplet变换的雷达回波微多普勒特征提取
算法
guygg889 小时前
采用PSO算法优化PID参数,通过调用Simulink和PSO使得ITAE标准最小化
算法
老鼠只爱大米9 小时前
LeetCode算法题详解 239:滑动窗口最大值
算法·leetcode·双端队列·滑动窗口·滑动窗口最大值·单调队列
J_liaty9 小时前
Spring Boot拦截器与过滤器深度解析
java·spring boot·后端·interceptor·filter
好好沉淀9 小时前
1.13草花互动面试
面试·职场和发展