FunctionRacerProblemsRace

Where the Cycle Starts

MediumLinked listsPython, JavaScript, TypeScript, Java, C++

Return the index (head is index 0) of the node where a cycle begins, meaning the first node you reach again if you keep following next forever. If the list has no cycle, return -1. In the tests the last node points back to the node at index pos, or to nothing when pos is -1; pos itself is not passed to your method. The list is passed in as head.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

head [3,2,0,-4]
returns 1

The last node points back to index 1.

Example 2

head [1,2]
returns -1

No cycle.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems