Linked List Cycle
EasyNeetCode 150Top Interview 150 Linked ListYahooProblem
You are given the head of a singly linked list. Sometimes the last node's arrow does not end at
null but points back at an earlier node, so walking the list never finishes.
Return true if the list loops back on itself, and false if it has an end.
In the examples the input shows the node values and pos, the index the last node points back to
(-1 means it points at null).
Constraints
- 0 ≤ number of nodes ≤ 10000
- -100000 ≤ Node.val ≤ 100000
- The cycle position pos is -1 or a valid index
Examples: pick one to animate
Solutions
Time: Without a cycle fast reaches the end in about n/2 steps. With one, fast gains one node per round on slow, so they meet within a few laps of the loop.
Space: Only the slow and fast pointers are kept.
Send one runner that moves one node per step and another that moves two. If the list has an end, the fast one falls off it. If the list loops, the fast one keeps gaining on the slow one inside the loop until they stand on the same node.