FastPrepLinked List Cycle Entry Node
Problem · Linked List

Linked List Cycle Entry Node

Learn this problem
MediumGoogle logoGoogleINTERNONSITE INTERVIEW
See Google hiring insights

Problem statement

A singly linked list is serialized by an integer array next. Node i points to node next[i]; a value of -1 means that node has no successor. Node 0 is the head, and every represented node is reachable by repeatedly following successors from the head before traversal stops or repeats a node.

If the list contains a cycle, return the zero-based index of the first node in that cycle. Otherwise, return -1.

Function

findCycleEntry(next: int[]) → int

Examples

Example 1

next = [1,2,3,1]return = 1

The traversal is 0 -> 1 -> 2 -> 3 -> 1. Node 1 is the first node in the cycle.

Example 2

next = [1,2,3,-1]return = -1

The traversal reaches node 3 and then stops, so the list has no cycle.

Example 3

next = [0]return = 0

The head points to itself, so node 0 is the cycle entry.

Constraints

  • 1 <= next.length <= 2 * 10^5.
  • Every next[i] is either -1 or an integer from 0 through next.length - 1.
  • Every represented node is reachable from node 0 before traversal stops or first repeats a node.

More Google problems

drafts saved locally
public int findCycleEntry(int[] next) {
  // write your code here
}
next[1,2,3,1]
expected1
checking account