Two pointers · Medium
A debugger represents a linked chain as indexes into a next-pointer table. Following the head should eventually reach null. Corrupt pointers can instead loop forever; unrelated cycles elsewhere in the table must not affect this head.
Return whether repeated next-pointer traversal starting at head enters a cycle using constant extra memory.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "next": (number|null)[], "head": number|null }.
Fields
- next[i] is null or another valid index. head is null or a valid index.
Output
Return value
- Return a boolean for the chain reachable from head only.
- A self-loop is a cycle. A null head or a chain ending at null returns false.
Constraints
- 0 <= next.length <= 100000. Empty next requires head=null.
- All pointers are within bounds; input validation is not assessed.
Examples
Example 1
{
"head": 0,
"next": [
1,
2,
1
]
}Returns
trueTraversal repeats index 1.
Example 2
{
"head": 0,
"next": [
null,
1
]
}Returns
falseThe cycle at 1 is not reachable.
Required complexity
O(n) time and O(1) extra space