40. Linked List Cycle
Easy · Linked List
Given a linked list encoded as an array of node values, determine if the linked list contains a cycle. For this problem, a cycle is indicated by a second parameter `pos` which represents the index (0-based) of the node that the tail connects back to. If `pos` is `-1`, there is no cycle.
Return `true` if the linked list has a cycle, and `false` otherwise.
Note: `pos` is not passed as a parameter to your function to traverse — it is only used to describe the structure of the input. Your task is simply to determine whether a cycle exists based on the given `pos` value.
Examples
Example 1 Input: nodes = [3, 2, 0, -4], pos = 1 Output: true Explanation: The tail node (-4) connects back to the node at index 1 (value 2), forming a cycle.
Example 2 Input: nodes = [1, 2], pos = -1 Output: false Explanation: There is no cycle; pos is -1 meaning the tail points to null.
Constraints
- Standard input/output constraints apply