codejump
MediumPythonJavaScriptTypeScript

Linked List — Where Does the Cycle Start?

Data StructuresLinked ListTwo Pointers

A singly linked list normally ends in null. A corrupted one has its last
node pointing back at an earlier node, so walking it never ends.

solve(values, pos) builds a list from values. If pos >= 0, the tail's
next is wired back to the node at index pos; if pos === -1 the list is
left intact. Return the index of the node where the cycle begins, or -1
when the list has no cycle.

Requirement: use O(1) extra space. A Set of visited nodes is the
obvious answer and is not accepted here — use Floyd's tortoise and hare.

Examples

solve([3, 2, 0, -4], 1)  → 1    // tail points back at the node holding 2
solve([1, 2],        0)  → 0    // tail points back at the head
solve([1],          -1)  → -1   // no cycle

Constraints

  • values may be empty (then the answer is -1).
  • Values may repeat, so compare nodes, never values.

Sample tests

Test #1Tail points back at the second node
Input: [[3,2,0,-4],1]
Output: 1
Test #2Tail points back at the head
Input: [[1,2],0]
Output: 0
Test #3A single node with no cycle
Input: [[1],-1]
Output: -1