FastPrepDetect a Linked-List Cycle

Detect a Linked-List Cycle

Google logoGoogle● EasyINTERNONSITE INTERVIEW
Learn

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 null. When the array is non-empty, node 0 is the head. Entries that are not reachable from node 0 are ignored.

Return true if following next pointers from the head eventually revisits a node. Return false for an empty list or when traversal reaches null.

Function

hasLinkedListCycle(next: int[]) → boolean

Examples

Example 1

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

Traversal from node 0 enters the cycle 1 -> 2 -> 3 -> 1.

Example 2

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

Traversal reaches node 3 and then null.

Example 3

next = [0]return = true

The head points to itself.

Example 4

next = []return = false

The empty array represents an empty list.

Constraints

  • 0 <= next.length <= 200000.
  • For every index i, next[i] == -1 or 0 <= next[i] < next.length.

More Google problems

See Google hiring insights
public boolean hasLinkedListCycle(int[] next) {
  // Write your code here.
}
next[1,2,3,1]
expectedtrue
Checking account…