Linked List Cycle
Problem Statement
Given 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. Return true if there is a cycle in the linked list. Otherwise, return false.
Constraints:
- The number of the 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
Input Format:
- The head of a linked list
- pos denotes the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle.
Output Format:
- Return true if there is a cycle in the linked list. Otherwise, return false.
Examples:
Example 1:
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).
Example 2:
Input:
head = [1,2], pos = 0
Output:
true
Explanation:
There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input:
head = [1], pos = -1
Output:
false
Explanation:
There is no cycle in the linked list.
Solutions
Floyd's Cycle-Finding Algorithm (Tortoise and Hare)
Use two pointers, a slow-moving pointer and a fast-moving pointer. If they ever meet, there's a cycle.
Hash Table Approach
Keep track of visited nodes using a hash set. If we encounter a node we've seen before, there's a cycle.
Algorithm Walkthrough
Example input: nums = []
Step-by-step execution:
- Create the linked list: 3 -> 2 -> 0 -> -4 -> (back to 2)
- Initialize slow = head (node with value 3), fast = head (node with value 3)
- Iteration 1:
- Move slow to next node: slow = node with value 2
- Move fast two steps: fast = node with value 0
- slow != fast, continue
- Iteration 2:
- Move slow to next node: slow = node with value 0
- Move fast two steps: fast = node with value 2 (cycled back)
- slow != fast, continue
- Iteration 3:
- Move slow to next node: slow = node with value -4
- Move fast two steps: fast = node with value -4
- slow == fast, we've detected a cycle
- Return true
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the slow and fast pointers moving through the linked list, with the slow pointer moving one step at a time and the fast pointer moving two steps at a time.
Key visualization elements:
- slow pointer
- fast pointer
- cycle detection
Implementation Notes
This is a classic problem that tests understanding of linked list traversal and cycle detection. Floyd's Cycle-Finding Algorithm (also known as Tortoise and Hare algorithm) is an elegant solution with O(1) space complexity.