Linked List Cycle
Determine if a linked list contains a cycle in O(n) time and O(1) space using Floyd's tortoise and hare algorithm.
01The problem
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. 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.
Can you solve it using O(1) (i.e. constant) memory?
| Input | Output | Why |
|---|---|---|
[3, 2, 0, -4], pos = 1 | true | Tail connects back to index 1 (value 2), forming loop |
[1, 2], pos = 0 | true | Tail connects back to index 0, forming two-node loop |
[1], pos = -1 | false | Single node points to null; no cycle |
[], pos = -1 | false | Empty list has no cycle |
Constraints: 0 to 10,000 nodes, node values between -100,000 and 100,000, pos is -1 or a valid index in the list.
Loading the rest of the lesson…