Skip to the solution
HardLow-Level DesignAsked in 20246 min read

Detect a Cycle in a Linked List (Floyd's Tortoise and Hare)

1.6k views

The problem

Problem, as an interviewer would state it: "Given the head of a linked list, determine whether it contains a cycle — using O(1) extra space, not a real Set tracking every visited node."

Examples:

Code
hasCycle(acyclicListHead); // false
hasCycle(cyclicListHead);  // true

Clarifying questions expected:

  • Is O(1) extra space genuinely required, or would an O(n)-space visited-set approach be acceptable?
  • Should this also work correctly for a single-node list, including one that points to itself?
  • Does the function need to return WHERE the cycle begins, or just whether one exists at all?

Code / implementation expected: Yes — real, direct proof across 5 real linked-list shapes: acyclic, genuinely cyclic, a single node, a self-referencing single node, and an empty list.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: hasCycle() produces the correct result across 5 real linked-list shapes, including a self-referencing single node and an empty list

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 140 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Build a Minimal jest.fn()-Style Spy/Mock Utility

Continue