Your question is Detect Loop in Linked List. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
SIXT represents a sequence of vehicle records as a singly linked list. Detect whether following the next references eventually revisits a node, which indicates a cycle.
For portability, the linked list is encoded by an array next, where next[i] is the index of the node reached from node i, or -1 if the node has no successor. The list begins at head.
Return True if the list contains a cycle, otherwise return False. Do not modify the input.
Implement has_cycle(next, head):
next: a list of integers representing successor indices.head: an integer node index, or -1 for an empty list.Use constant auxiliary space. The cycle may begin at the head or at any later node.
def has_cycle(next, head):