Linked List Cycle
easyLinked List+10 XPTime limit 2s
Does the linked list contain a cycle — a node whose next pointer leads back to an earlier node, so walking the list never ends?
List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.
Input: one list, then a third line pos: the 0-based index of the node that the tail points back to, or -1 if the tail points to nothing. (The starter code builds the list and links the tail for you.)
Output: true if there is a cycle, otherwise false.
Constraints: 0 ≤ n ≤ 10⁵, −1 ≤ pos < n.
Rules of the game: of course the answer is just "pos ≠ −1" — but that's not the point! Solve it on the nodes without using pos: Floyd's tortoise and hare. If the fast pointer ever meets the slow one, there is a cycle. O(1) extra memory.
Sample input 1
4 3 2 0 -4 1
Sample output 1
true
Sample input 2
2 1 2 0
Sample output 2
true
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).