Detect a Cycle in a Linked List
Updated
Problem statement
Determine whether a singly linked list contains a cycle reachable from its head.
For this exercise, links are encoded by an array next. Node IDs are the zero-based array indices. next[i] gives the next node after node i, or -1 if there is no next node. The head is node 0 when the array is nonempty; an empty array represents an empty list. Only follow nodes that can be reached from the head. Ignore all other nodes in the table.
Return true if following the next-node links from the head eventually repeats a node; otherwise return false.
Function
hasCycle(next: int[]) → booleanExamples
Example 1
next = [1,2,3,1]return = trueThe walk is 0 → 1 → 2 → 3 → 1, which repeats node 1.
Example 2
next = [2,-1,1]return = falseThe walk is 0 → 2 → 1 and then terminates. Node IDs do not have to appear in traversal order.
Constraints
- For this exercise, assume
0 <= next.length <= 10^5. - Each entry is
-1or a valid node ID smaller thannext.length.
More PeopleStrong Onsite Interview questions
- Add Two Binary StringsONSITE INTERVIEW · Seen Mar 2026
- Four SumONSITE INTERVIEW · Seen Mar 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Mar 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Mar 2026
- Find the Entry of a Linked List CycleONSITE INTERVIEW · Seen Sep 2025
- Integer to English Words: Up to 20 DigitsONSITE INTERVIEW · Seen Sep 2025
- Word Ladder II: All Shortest TransformationsONSITE INTERVIEW · Seen Sep 2025
- First Nonrepeating CharacterONSITE INTERVIEW · Seen May 2025
- Longest Subarray with a Target SumONSITE INTERVIEW · Seen May 2025
- Lowest Common Ancestor in a BSTONSITE INTERVIEW · Seen May 2025
Similar questions at other companies
- Detect a Loop in a Linked ListEPAM · ONSITE INTERVIEWEPAM interview questions
- Merge Two Sorted Linked ListsZS · ONSITE INTERVIEWZS interview questions
- Middle Node Of A Linked ListNVIDIA · ONSITE INTERVIEWNVIDIA interview questions
- Build and Check a Palindrome Linked ListOmnissa · ONSITE INTERVIEWOmnissa interview questions
- Reverse a Singly Linked ListGEP · ONSITE INTERVIEW
- Merge Two Sorted Linked ListsApple · ONSITE INTERVIEWApple interview questions
- Reverse a Singly Linked ListMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Reverse Linked ListThe Walt Disney Company · OA · ONSITE INTERVIEWThe Walt Disney Company interview questions
- Detect a Linked-List CycleGoogle · ONSITE INTERVIEWGoogle interview questions
- Reverse a Singly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions