Skip to the solution
MediumDSA13 min read

How do you find the node where a linked list cycle begins?

607 views

The problem

Question presented to candidate: "You are given the head of a singly linked list that may contain a cycle. Return the node where the cycle begins, or None if there is no cycle. Can you do it without extra memory? Please write it in Python."

What a strong answer should cover:

  • A hash-set baseline (first node seen twice is the entry), O(n) time and O(n) space.
  • Floyd's tortoise and hare: slow moves 1, fast moves 2; when they meet, restart one pointer at the head and move both by 1 until they meet at the entry.
  • Why phase 2 works: the meeting distance is a multiple of the cycle length, so mu more steps from the meeting point land on the entry. O(n) time, O(1) space.
  • Edge cases: empty list, single node with and without a self-loop, cycle back to the head, duplicate values.
  • Python specifics: compare nodes with is, not ==; a plain class hashes by identity so set() works, but a @dataclass node defines __eq__ and becomes unhashable.

Clarifying questions expected:

  • "Return the node, or an index? What if there is no cycle?"
  • "Is O(n) extra memory allowed, and may I modify the list?"

Code / implementation expected: Yes โ€” detect_cycle(head) in Python with two pointers and no extra data structures.

  • linked-list
  • cycle

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

13 min read ยท 11 sections

Python code

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

PythonFloyd on lists with and without a cycle
PythonPhase step counts, and Floyd versus a hash set

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 80 of 154 in DSA

Keep your momentum going.

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

All DSA questions
Up nextMedium

What is a greedy algorithm?

Continue