Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
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 (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
pos is -1 or a valid index in the linked-list.Follow up: Can you solve it using O(1) (i.e. constant) memory?
One straightforward way to determine if there's a cycle in a linked list is to keep track of nodes we've already visited. If we encounter a node we've already seen, there's a cycle. This can be achieved using a HashSet where we store each visited node.
HashSet to keep track of visited nodes.HashSet.HashSet and continue.null), then there is no cycle.O(n), where n is the number of nodes in the linked list, because each node is visited at most once.O(n) due to the space required for storing visited nodes in the HashSet.The Tortoise and Hare algorithm is an optimized method to detect cycles using two pointers. One pointer (the tortoise) moves one step at a time while the other pointer (the hare) moves two steps at a time. If there is a cycle, the hare will eventually meet the tortoise within the cycle.
Once a cycle is detected, reset one pointer to the start of the list and keep the other pointer at the meeting point. Move both pointers one step at a time. The point where they meet again is the start of the cycle.
slow and fast.slow by one step and fast by two steps in the list.fast or fast.next becomes null, there's no cycle.slow to the head of the list and move both slow and fast one step at a time; the node where they meet is the start of the cycle.O(n), as each node is visited at most twice.O(1), since no additional data structures are used for storage.