Algorithm-Day25-Linked-List-Cycle-lc-141
🧩 Problem Description
Given the head
of a linked list, determine if the linked list has a cycle in it.
A cycle occurs when a node’s next
pointer points to a previous node in the list.
Example:
1 | Input: head = [3,2,0,-4], pos = 1 (tail connects to node index 1) |
💡 Brute Force (Not Recommended)
- Store visited nodes in a
HashSet
. - If a node is already visited → cycle detected.
1 | public boolean hasCycle(ListNode head) { |
- Time: O(n)
- Space: O(n)
💡 Optimal Approach: Floyd’s Tortoise and Hare
✨ Key Idea
- Use two pointers:
slow
moves 1 stepfast
moves 2 steps
- If there’s a cycle,
fast
will eventually “lap”slow
. - If
fast
reachesnull
, the list has no cycle.
🔢 Java Code (Two-Pointer Approach)
1 | public class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
✍️ Summary
- This problem is a classic use case for Floyd’s Cycle Detection Algorithm.
- Know the difference:
lc-141
: Detect existence of a cyclelc-142
: Find the starting node of the cycle
Learn the two-pointer cycle detection — it’s elegant and appears in many linked list problems.