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.

相关推荐
JH30736 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
颜酱7 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_736919107 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi9878387 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
Coder_Boy_7 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
DuHz7 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
invicinble7 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
Polaris北极星少女8 小时前
TRSV优化2
算法
较真的菜鸟8 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖8 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言