Fast and slow pointers for cycle detection in linked list

The blog aims to provide a sound proof for the approach to solve leetcode 142.

Problem

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

Most programmers know that the fast/slow pointers approach is able to detect cycle in a singly linked list. If two pointers finally meet somewhere then we are sure a cycle exists. And if we set one pointer at the list head and another at meeting point and let them go in the same speed, then they will meet again at the starting point of the cycle.

Does this approach work? I will try to give you a proof of it.

Fast and slow pointers for cycle detection in linked list

See the graph above, let L, M, N denote distance. Now let's suppose the fast pointer travels x times in the cycle and the slow one go around the cycle y times when they meet, then the following equation holds:

L+M+(M+N)x=2[L+M+(M+N)y]

After some cancelling we could get:

L=N+(M+N)(x-2y-1)

What does it mean? Remember the method to find the start point? The first pointer starts at the list head and the second starts at meeting point, when the first arrives at the cycle start, it travels for L distance, and the second pointer in the meantime travels several rounds of the cycle plus N distance. It's guaranteed they would meet at the cycle start.

In a tiktok interview the interviewer asked me to prove the correctness of the algorithm and this was my solution.

上一篇:1150 Travelling Salesman Problem


下一篇:做商标转让公证有什么用呢?