We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Loop 4: slow = E, fast = E; (slow == fast => cycle found!)
The fast pointer is skipping every other node (fast.next.next) while the slow pointer is stepping through each node one at a time (slow.next). If the fast pointer gets stuck in a cycle, we will eventually reach a point where the slow pointer "catches up" and equals the fast pointer - which can only happen if there's a cycle.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Linked Lists: Detect a Cycle
You are viewing a single comment's thread. Return to all comments →
Draw a picture.
Start: slow = A, fast = A
Loop 1: slow = B, fast = C
Loop 2: slow = C, fast = E
Loop 3: slow = D, fast = C
Loop 4: slow = E, fast = E; (slow == fast => cycle found!)
The fast pointer is skipping every other node (fast.next.next) while the slow pointer is stepping through each node one at a time (slow.next). If the fast pointer gets stuck in a cycle, we will eventually reach a point where the slow pointer "catches up" and equals the fast pointer - which can only happen if there's a cycle.