Linked list · Medium
A chain preview lists distinct reachable records and stops before the first repeated node. A user selects a one-based position from the end of that finite preview. The stored values may repeat, so the traversal must keep node indexes separate from their payloads.
Return the stored value k positions from the end of the distinct reachable traversal or null when that preview has no such position.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ next: (integer | null)[], values: integer[], head: integer | null, k: integer }
Fields
- next is an array of next-node indexes or null; head is the starting index or null.
- Every non-null pointer is in bounds. Disconnected nodes may exist, and reachable nodes may form a cycle.
- values has the same length as next and stores one signed integer per node. k is a one-based position from the end.
Output
Return value
- Follow pointers until null or just before the first repeated index. Select from this finite sequence, not from the backing array.
- k = 1 selects its last visited value. k < 1 or k greater than preview length returns null; repeated payload values still belong to distinct nodes.
Constraints
- 0 <= next.length <= 100000. Node identity is its index, not its stored value.
- Do not mutate pointers or input arrays. Only nodes reachable from head contribute.
- values.length = next.length; -1000000000 <= values[i] <= 1000000000; -1 <= k <= 100001.
Examples
Example 1
{
"head": 0,
"k": 2,
"next": [
2,
null,
1
],
"values": [
10,
20,
30
]
}Returns
30Example 2
{
"head": 0,
"k": 1,
"next": [
1,
2,
1
],
"values": [
4,
5,
6
]
}Returns
6Required complexity
O(r) time and O(r) auxiliary space for r distinct reachable nodes