Assuming standard inputs and constraints as per typical LeetCode problems:
We can use Floyd’s Tortoise and Hare Algorithm to detect the start of the cycle in the linked list. The main idea is as follows:
slow
and fast
. slow
moves one step at a time while fast
moves two steps at a time.slow
and fast
will eventually meet inside the cycle.slow
to the head of the list.slow
and fast
one step at a time; the node where they meet now is the start of the cycle.Let’s implement this in Python:
# Definition for singly-linked list node.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def detectCycle(head: ListNode) -> ListNode:
if not head or not head.next:
return None
slow, fast = head, head
# Phase 1: Determine whether a cycle is present.
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# Cycle detected
break
else:
# No cycle detected
return None
# Phase 2: Find the start of the cycle.
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
The time complexity of this approach is O(n)
, where n
is the number of nodes in the linked list:
O(n)
steps combined.O(n)
steps.The space complexity is O(1)
because we only use a fixed amount of additional space (pointers).
By following this strategy and implementation, we ensure an efficient and clear solution to the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?