FastPrepDetect a Linked-List Cycle

Detect a Linked-List Cycle

Capgemini logoCapgemini● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A linked list is encoded by nextIndex: node i points to node nextIndex[i], and -1 marks the end. Traversal starts at node 0.

Return whether the reachable chain contains a cycle. An empty array represents an empty list.

Function

hasCycle(nextIndex: int[]) → boolean

Examples

Example 1

nextIndex = [-1]return = false

Case 1 exercises the documented deterministic contract.

Example 2

nextIndex = [1,2,-1]return = false

Case 2 exercises the documented deterministic contract.

Example 3

nextIndex = [1,2,0]return = true

Case 3 exercises the documented deterministic contract.

Constraints

  • 0 <= nextIndex.length <= 200000.
  • Every value is -1 or a valid node index.

More Capgemini problems

See Capgemini hiring insights
public boolean hasCycle(int[] nextIndex) {
    // Write your code here.
}
nextIndex[-1]
expectedfalse
Checking account…