See the original problem on HackerRank.
Solutions
An efficient solution is based on the “two pointers idiom”.
We traverse the list using two pointers that we’ll refer to as fast and slow. Our slow pointer moves forward 1 node at a time, and our fast pointer moves forward 2 nodes at a time. If at any point in time these pointers refer to the same object, then there is a loop; otherwise, the list does not contain a loop.
C++ implementation:
|
|
Ptyhon implementation:
|
|
Further readings: