Find a Linked-List Cycle Entrance
Find where a linked list's cycle begins with fast and slow pointers in O(1) extra space.
The problem
Implement Solution.detectCycle(nextIndices). The list is given as an array of next pointers: node 0 is the head, and nextIndices[i] is the index of the node after node i, or None if node i is the last node. If the list has a cycle, return the index of the node where the cycle begins; otherwise return -1. For example, [1, 2, 3, 1] is 0 -> 1 -> 2 -> 3 -> back to 1, so the answer is 1. An empty array is an empty list. Do not modify nextIndices. There are at most 10,000 nodes. Try to use only O(1) extra space.
Starter code
class Solution:
def detectCycle(self, nextIndices):
passPublic examples
nextIndices = [1, 2, 3, 1]gives1nextIndices = [1, 0]gives0nextIndices = [1, 2, 3, 4, 2]gives2
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
