Question presented to candidate: "Given the head of a singly linked list, reverse it and return the new head. Write it in Python, and tell me how much extra memory it uses."
What a strong answer should cover:
- The idea: walk the list once and point every node's
nextat the node before it, so the old tail becomes the head. - Three pointers (
prev,curr,next) and why the next node must be saved before the arrow is flipped. - O(n) time and O(1) extra space for the iterative version; the recursive version is O(n) time but O(n) call-stack space.
- Edge cases: empty list, one node, two nodes, and returning the new head rather than the old one.
- Python specifics: a small
ListNodeclass,is Nonechecks, why the order of a one-line tuple assignment matters, and why recursion fails past CPython's default limit of about 1,000 frames.
Clarifying questions expected:
- "Singly or doubly linked, and may I change the nodes in place or must I build a new list?"
- "How long can the list be? That decides whether recursion is safe."
Code / implementation expected: Yes โ a Python reverse_list(head) with prev / curr / nxt, ideally plus the recursive version and its stack cost.