41. Linked List Cycle II
Medium · Linked List
Given a linked list, determine if the list contains a cycle. If a cycle exists, return the node at the beginning of the cycle. If no cycle exists, return null.
A cycle occurs when a node's next pointer eventually leads back to a previous node in the list, creating a loop. You must detect both the presence of a cycle and identify the exact node where the cycle begins.
Examples
Example 1 Input: List: 3 → 2 → 0 → -4 → (back to node 2) Output: Node with value 2 Explanation: The list has a cycle that begins at the node with value 2. Starting from the head (3), following next pointers eventually loops back to the node containing 2.
Example 2 Input: List: 1 → 2 → 3 → 4 → 5 (no cycle) Output: null Explanation: The list is linear with no cycle. The last node (5) points to null, so there is no loop.
Constraints
- Standard input/output constraints apply