Question presented to candidate: "You are given the heads of two linked lists, each already sorted in ascending order. Merge them into one sorted list by splicing the existing nodes together, and return its head. Please write it in Python."
What a strong answer should cover:
- The idea: the smallest remaining value is always at the front of one of the two lists, so repeatedly take the smaller front node.
- A dummy (sentinel) node and a
tailpointer, which remove the special case for the first node. - Attaching the leftover list in one step when the other runs out.
- O(m + n) time and O(1) extra space for the loop; the recursive version uses O(m + n) stack.
- Stability: using
<=so equal values keep listafirst. - Python specifics:
is Nonechecks,<=for stability, whyheapq.mergedoes not apply to node objects, and the recursion limit for the recursive version.
Clarifying questions expected:
- "Can I reuse the input nodes, or must the original lists stay intact?"
- "Are there duplicates, and if so should ties come from the first list?"
Code / implementation expected: Yes โ a Python merge_two_lists(a, b) with a dummy node, plus the recursive version if time allows.