Linked List Cycle
Given the head of a linked list, determine whether the list contains a cycle — that is, whether some node's next pointer eventually revisits an earlier node. Return true if a cycle exists, otherwise false.
Open official problem prompt ↗Report whether following next pointers ever loops, without recording every visited node.
Two runners on a track: if the track is a loop, the faster runner eventually laps and meets the slower one; on a straight track the fast runner just finishes and there is no meeting.
- Input
- head = [3, 2, 0, -4] with the tail's next connected to index 1
- Output
- true
- Why
- Following next from -4 returns to node 2, so the traversal loops forever — a cycle exists.
The number of nodes is in the range [0, 10^4]-10^5 <= Node.val <= 10^5pos is -1 (no cycle) or a valid index into the list