Detect a Cycle in a Linked List
Updated
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 input uses indices to identify nodes. 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 follow nodes that can be reached from head. Ignore all other 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) → booleanExamples
Example 1
next = [1,2,1]head = 0return = trueThe successor walk revisits node 1, so the reachable list has a cycle.
Example 2
next = [1,2,-1]head = 0return = falseThe successor walk reaches null without repeating a node.
Example 3
next = []head = -1return = falseAn empty list has no reachable cycle.
Constraints
0 <= next.length <= 100000.- Every successor is
-1or an index innext. headis-1or a valid node index; an empty array hashead = -1.
More Salesforce Phone Screen questions
- Find Rows Common to Two TablesPHONE SCREEN · Seen Oct 2026
- Merge Two Sorted Linked ListsPHONE SCREEN · Seen Oct 2026
- Minimum Window of Required WordsPHONE SCREEN · Seen Aug 2026
- Permutations of Unique CharactersPHONE SCREEN · Seen Aug 2026
- Minimum Window SubstringPHONE SCREEN · Seen Aug 2026
- Optimal Account BalancingPHONE SCREEN · Seen Jul 2026
- Longest Increasing SubsequencePHONE SCREEN · Seen Jul 2026
- Maximal SquarePHONE SCREEN · Seen Jul 2026
- ATM Queue Exit OrderPHONE SCREEN · Seen May 2026
- Good Ways to Split an ArrayPHONE SCREEN · Seen May 2026
Similar questions at other companies
- Merge Two Sorted ListsLinkedIn · PHONE SCREENLinkedIn interview questions
- Middle of a Linked ListCisco · PHONE SCREENCisco interview questions
- Merge Two Sorted ListsIBM · PHONE SCREENIBM interview questions
- Count Nodes in a ChainApple · PHONE SCREENApple interview questions
- Find the Intersection Node of Two Linked ListsVisa · PHONE SCREENVisa interview questions
- Reverse a Linked ListMygate · PHONE SCREENMygate interview questions
- Linked List Palindrome in Constant SpaceNVIDIA · PHONE SCREENNVIDIA interview questions
- First Node Two Linked Lists ShareAdobe · PHONE SCREENAdobe interview questions
- Reverse a Singly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Merge Two Sorted Linked ListsExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions