Detect a Linked-List Cycle
Updated
Problem statement
A linked list is stored in an array nextIndex. Node i points to node nextIndex[i], and -1 means the list ends there. Start at node 0 and follow the pointers.
Return true if following the pointers from the start ever loops back to a node you already visited. Otherwise return false. An empty array is an empty list.
Function
hasCycle(nextIndex: int[]) → booleanExamples
Example 1
nextIndex = [-1]return = falseCase 1: the list has one node and its next pointer is the end marker, so the walk stops right away. There is no cycle, so the answer is false.
Example 2
nextIndex = [1,2,-1]return = falseCase 2: node zero points to node one, node one points to node two, and node two is the end marker. The walk finishes without revisiting a node, so the answer is false.
Example 3
nextIndex = [1,2,0]return = trueCase 3: node zero points to node one, node one to node two, and node two points back to node zero. The walk returns to a node it already saw, so the answer is true.
Constraints
0 <= nextIndex.length <= 200000.- Every value is
-1or a valid node index.
More Microsoft Onsite Interview questions
- Bad Request AlertsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Detect a Linked-List CyclePaytm · ONSITE INTERVIEWPaytm interview questions
- Detect a Linked-List CycleCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Detect and Remove a Linked List LoopBank of America · ONSITE INTERVIEWBank of America interview questions
- Find a Linked-List Cycle EntryExpedia · ONSITE INTERVIEWExpedia interview questions
- First Node Two Linked Lists ShareAdobe · PHONE SCREENAdobe interview questions
- Check a Linked List for a CycleZillow · PHONE SCREENZillow interview questions
- Where Two Linked Lists MeetNutanix · PHONE SCREENNutanix interview questions
- LRU CacheApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- LRU CacheServiceNow · PHONE SCREEN · ONSITE INTERVIEWServiceNow interview questions