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
slowis in the middle whenfastruns 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, thefast is not None and fast.next is not Noneorder, and nolen()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.