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.

相关推荐
鱼跃鹰飞23 分钟前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
没差c43 分钟前
springboot集成flyway
java·spring boot·后端
时艰.1 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音1 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
编程彩机1 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪1 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
筵陌2 小时前
算法:模拟
算法
Yvonne爱编码2 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
We་ct2 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
renhongxia12 小时前
AI算法实战:逻辑回归在风控场景中的应用
人工智能·深度学习·算法·机器学习·信息可视化·语言模型·逻辑回归