Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up: Can you solve it without using extra space?

Hashset approach:
A trick one is to use slow/fast runner. Slow runner moves forward one step where fast runner moves forward two steps. If there is a cycle they will eventually meet. Suppose that the cycle size is c, and the distance between the head and the begin node of the cycle is x. When the slow runner meets the fast runner, the slow runner moves y steps and the fast one moves 2y steps. Then we have
y = x + k1*c + b
2y = x + k2*c + b
x + b = k*c
Now we move the slow runner to the head and keep the fast runner at the place they meet. The distance between two runners are x + b; since the distance can be divided by c, if we move both runners at the same pace, they will meet at the beginning of the cycle. 

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design