Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Where a linked list loops back on itself

Medium · Target 15 minutes · Two pointers· Type asked at

A singly linked list is stored as an array next, where next[i] is the index of the node after node i, or −1 if node i is the last one. The list starts at node 0. If following it from node 0 goes round a cycle, return the index of the first node of that cycle (the first node you reach twice). If the list ends, return −1. You should only use O(1) extra space.

Examples

InputOutputWhy
next = [1, 2, 3, 1]1The list goes 0 → 1 → 2 → 3 and then back to 1, so it's at 1 that the cycle starts.
next = [1, -1]-10 → 1 and then the list ends, so there's no cycle.
next = [0]0Node 0 points to itself, which is a cycle of length one.

Constraints

  • 1 ≤ n ≤ 10⁴
  • −1 ≤ next[i] < n

Hints

Hint 1

A set of the nodes you've visited would do it in O(n) space. How would you even tell whether there's a cycle without remembering anything?

Hint 2

Run a slow pointer one step at a time and a fast one two steps. If fast falls off the end there's no cycle. If there's a cycle they'll meet in it.

Hint 3

Once they've met, put one pointer back at node 0 and move both one step at a time. The node where they meet now is where the cycle starts.

Where people lose marks

  • Moving fast two steps without checking the first one. If next[fast] is −1 you can't go on to look up next[−1], so you've got to check before each of the two steps.
  • Returning the node where they first met, which is on the cycle all right but it's only the first node of it if the path in happens to be the right length.
  • Starting slow and fast on the same node with the check at the top of the loop, so that they're equal straight away and you'd report a cycle that isn't there.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.