Loading…
Loading…
Given a linked list, print true if it contains a cycle (some node's next eventually points back to an earlier node), false otherwise.
Input: values 3 2 0 -4, cycle connects back to index 1
Output: true
Floyd's cycle detection ("tortoise and hare"): one pointer moves one step at a time, another moves two. If there's a cycle, the fast pointer will eventually lap the slow one and they'll meet inside the loop; if there's no cycle, the fast pointer simply reaches the end. This uses O(1) extra memory, unlike tracking visited nodes in a set.
Line 1: the list values, space-separated
Line 2: the index the last node's next should connect back to, or -1 for no cycle
Print true or false.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.