All problems
Cycle Length in Linked List
Problem
Find the length of the cycle in a linked list, or 0 when there is none.
values holds the node values and pos is the index the tail links back to, or -1 for no cycle. Use Floyd's tortoise and hare to find a meeting point, then walk the cycle from that point until returning to it while counting nodes.
Return the number of nodes in the cycle.
Hint
Once the pointers meet, walk one pointer around the loop until it returns to the meeting node.
Test cases
case 1
in: [[3,2,0,-4],1]
expected: 3
case 2
in: [[1,2],0]
expected: 2
case 3
in: [[1],0]
expected: 1
case 4
in: [[1,2,3],-1]
expected: 0
case 5
in: [[],-1]
expected: 0
Starter codePython
def cycle_length(values, pos):
# Your code here
pass5 test cases · run your code against them in the editor