FastPrepDetect a Loop in a Linked List

Detect a Loop in a Linked List

EPAM logoEPAM● EasyINTERNONSITE INTERVIEW

Problem statement

A singly linked list is described by node indices. There are n = nextIndices.length allocated nodes, numbered 0 through n - 1. For each node i, nextIndices[i] is the index of its next node, or -1 when its next pointer is null.

The list starts at head. A head of -1 means an empty list, even if other nodes are allocated. Only nodes reachable by following next pointers from the head belong to the list; other allocated nodes do not affect the answer.

Return true if following next pointers from the head eventually revisits a node. Return false if it reaches null. Do not change any next pointer.

Function

hasCycle(nextIndices: int[], head: int) → boolean

Examples

Example 1

nextIndices = [1,2,1]head = 0return = true

The reachable path is 0 → 1 → 2 → 1. Node 1 is visited again, so the list has a cycle.

Example 2

nextIndices = [1,2,-1,3]head = 0return = false

The reachable path is 0 → 1 → 2 → null. Node 3 points to itself, but it is not reachable from head 0 and does not make this list cyclic.

Example 3

nextIndices = []head = -1return = false

The head is null, so there is no node to revisit.

Constraints

  • 0 <= nextIndices.length <= 10^5.
  • Every element of nextIndices is -1 or a valid node index.
  • -1 <= head < nextIndices.length.

More EPAM problems

See EPAM hiring insights
Saved
public boolean hasCycle(int[] nextIndices, int head) {
    return false;
}
Checking account…