FastPrepDetect a Cycle in a Linked List

Detect a Cycle in a Linked List

Salesforce logoSalesforce● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Determine whether a singly linked list contains a cycle reachable from its head. Return true if repeatedly following next links ever visits the same node again; otherwise return false.

The finite input preserves node identity with indices. next[i] is the index of node i's successor, or -1 for null. head is the first node index, or -1 for an empty list. Different indices represent different nodes even when their values would match. No node values are needed to detect a cycle.

Only nodes reachable from head belong to the list being queried; ignore disconnected nodes. Links may point to any valid node index, including the same node. For this exercise, assume the supplied indices are valid and do not change.

Function

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

Examples

Example 1

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

The successor walk revisits node 1, so the reachable list has a cycle.

Example 2

next = [1,2,-1]head = 0return = false

The successor walk reaches null without repeating a node.

Example 3

next = []head = -1return = false

An empty list has no reachable cycle.

Constraints

  • 0 <= next.length <= 100000.
  • Every successor is -1 or an index in next.
  • head is -1 or a valid node index; an empty array has head = -1.

More Salesforce problems

See Salesforce hiring insights
public boolean hasCycle(int[] next, int head) {
    // Write your code here.
}
next[1,2,1]
head0
expectedtrue
Checking account…