Menu
CoddyTech

Linked List Cycle

A linked list is stored in the array next: node i links to node next[i], and -1 means the list ends there. The head is node 0. Follow the links from the head and return true if you ever come back to a node you have already visited, or false if you reach the end. Nodes the walk never reaches do not count, even if they link to each other in a loop.

Function

hasCycle(next: integer-array) → boolean
nextinteger-array
the link of every node: next[i] is the node after node i, or -1
Returnsboolean
true if the walk from node 0 revisits a node, false if it reaches -1

Constraints

  • 1 ≤ next.length ≤ 104
  • -1 ≤ next[i] ≤ next.length-1
  • Several nodes may link to the same node, and some nodes may be unreachable from the head.

Examples

Input
next = [1, 2, 3, 1]
Output
true
Explanation
The walk goes 0, 1, 2, 3 and then back to 1. Node 1 is visited twice, so the list has a cycle through nodes 1, 2 and 3.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

Can you also find the node where the cycle begins, still with O(1) extra memory?

Reset code
def hasCycle(next):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

next = [1, 2, 3, 1]

Expected

true