Question presented to candidate: "Given the head of a singly linked list, remove the nth node from the end and return the head. For 1, 2, 3, 4, 5 and n = 2 the answer is 1, 2, 3, 5. Can you do it in one pass? Please write it in Python."
What a strong answer should cover:
- The two-pass baseline: count the length, then unlink the node at index length - n.
- The one-pass version: a dummy node,
fastmoved n + 1 links ahead, then both pointers move untilfastis None;slowis the predecessor of the target. - Why the dummy node matters: removing the head (n = length) needs no special case.
- O(L) time and O(1) space for both, and an honest note that "one pass" does not mean fewer pointer moves.
- Python specifics:
ListNode(0, head)as the dummy,for _ in range(n + 1), and the unlinked node is reclaimed by the garbage collector once nothing refers to it.
Clarifying questions expected:
- "Is n 1-based and always between 1 and the length?"
- "Should I return the new head?"
Code / implementation expected: Yes โ remove_nth_from_end(head, n) in Python, one pass.