1605. Lasso Kth Step

Medium3.5 points estimatedLinked ListTwo PointersMaths

A toy train follows a track stored as a linked list. Starting at head (step 1), it moves along next pointers one node per step. The track may end in a loop: the last node's next can point back to some earlier node, so the train circles forever. Given head and a very large step number k, return the node the train is on at step k, by reference.

If the track has no loop and k is larger than its length, return null. Otherwise use Floyd's algorithm to find the length t of the tail before the loop and the loop length c; for k > t the node at step k is step t + ((k - t - 1) mod c) + 1. Never walk k steps.

Example 1

Input:
head = {"values":[3,2,0,-4],"pos":1}, k = 10
Output:
3
Explanation:

The tail has length 1 and the loop has 3 nodes; step 10 lands on the node with value -4.

Example 2

Input:
head = {"values":[1,2,3],"pos":-1}, k = 5
Output:
null
Explanation:

The list has no loop and only 3 nodes, so step 5 does not exist and the answer is null.

Constraints

1 ≤ length ≤ 1000; 1 ≤ k ≤ 1015; node values fit in a 32-bit signed integer. The list is given as values plus pos, the index the last node links back to (-1 for no loop).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…