Skip to the solution
EasyDSA11 min read

How do you find the middle of a linked list?

775 views

The problem

Question presented to candidate: "Given the head of a singly linked list, return its middle node. If the list has an even number of nodes, return the second of the two middle nodes. Please do it in Python, in one pass if you can."

What a strong answer should cover:

  • The baseline: count the nodes, then walk half way (two passes, O(1) space), or copy into an array (O(n) space).
  • The one-pass fast and slow pointer loop, and why slow is in the middle when fast runs out.
  • Even lengths: which middle each starting position gives, and how to get the other one.
  • O(n) time and O(1) space, and the honest point that fast/slow does about as many pointer hops as two passes.
  • Python specifics: // for the index in the array version, the fast is not None and fast.next is not None order, and no len() on a hand-made node class.

Clarifying questions expected:

  • "For an even length, should I return the first or the second middle?"
  • "Should I return the node or its value, and what for an empty list?"

Code / implementation expected: Yes โ€” a Python middle(head) with slow and fast pointers, and a note on the first-middle variant.

  • linked-list
  • two-pointers

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

11 min read ยท 11 sections

Python code

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

PythonFirst and second middle for every length from 0 to 6
PythonCopy to array vs two passes vs fast/slow: hops and memory

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 15 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 nextEasy

What is the time complexity of common operations on arrays, hash maps, and balanced trees?

Continue