Linked List Cycle
Linked List Cycle
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. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Function signature
func HasCycle(head *ListNode) bool
ListNode definition
type ListNode struct {
Val int
Next *ListNode
}
Examples
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle where tail connects to node index 1.
3 -> 2 -> 0 -> -4
^ |
|__________|
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: Tail connects to node index 0.
1 -> 2
^ |
|____|
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle.
1 -> nil
Constraints
- The number of nodes in the list is in the range [0, 10000]
- -100000 <= Node.val <= 100000
- pos is -1 or a valid index in the linked-list
Hints
- Use Floyd's cycle detection algorithm (fast and slow pointers).
- If there's a cycle, the fast pointer will eventually catch up to the slow pointer.
- If there's no cycle, the fast pointer will reach the end (nil).
Notes
- This is Floyd's Tortoise and Hare algorithm.
- O(n) time complexity, O(1) space complexity.
- The slow pointer moves 1 step, fast pointer moves 2 steps per iteration.
Follow-up
Can you solve it using O(1) (constant) memory?
Run tests to see results
No issues detected