two pointers
linked list
]
Leetcode 0142. Linked List Cycle II
https://leetcode.com/problems/linked-list-cycle-ii
This is very classical problem for two pointers approach: we use slow and fast pointers: slow which moves one step at a time and fast, which moves two times at a time. To find the place where loop started, we need to do it in two iterations: first we wait until fast pointer gains slow pointer and then we move slow pointer to the start and run them with the same speed and wait until they concide.
Complexity: time complexity is O(n)
, because we traverse our linked list twice, space complexity is O(1)
, because we do not create any additional variables.
class Solution:
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast: break
if not fast or not fast.next: return None
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
PS see also Problem 287. Find the Duplicate Number: https://leetcode.com/problems/find-the-duplicate-number/discuss/704693/Python-2-solutions%3A-Linked-List-Cycle-O(n)-and-BS-O(n-log-n)-explained which uses the same idea.
If you like the solution, you can upvote it on leetcode discussion section: Problem 0142