Detect a Linked-List Cycle
Updated
Problem statement
A singly linked list is serialized by an integer array next. Node i points to node next[i]; a value of -1 means null. When the array is non-empty, node 0 is the head. Entries that are not reachable from node 0 are ignored.
Return true if following next pointers from the head eventually revisits a node. Return false for an empty list or when traversal reaches null.
Function
hasLinkedListCycle(next: int[]) → booleanExamples
Example 1
next = [1,2,3,1]return = trueTraversal from node 0 enters the cycle 1 -> 2 -> 3 -> 1.
Example 2
next = [1,2,3,-1]return = falseTraversal reaches node 3 and then null.
Example 3
next = [0]return = trueThe head points to itself.
Example 4
next = []return = falseThe empty array represents an empty list.
Constraints
0 <= next.length <= 200000.- For every index
i,next[i] == -1or0 <= next[i] < next.length.
More Google Onsite Interview questions
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
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 Cycle in a Linked ListPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Reverse a Singly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions