Linked list · Easy
A linked-record preview must stop at the first repeated node or at the end of the chain. The backing array can contain unrelated records that are not part of this preview. Counting array length or traversed links would give the wrong number of visible records.
Count distinct node indexes visited from head before reaching null or attempting to revisit an already seen node.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ next: (integer | null)[], head: integer | null }
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.
Output
Return value
- Return the number of distinct reachable nodes, including the head when present.
- Count cycle nodes once and ignore all disconnected nodes. A null head returns zero.
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.
Examples
Example 1
{
"head": 0,
"next": [
1,
2,
1,
null
]
}Returns
3Example 2
{
"head": 1,
"next": [
null,
null
]
}Returns
1Required complexity
O(r) time and O(r) auxiliary space for r distinct reachable nodes