Python coding

Splice two sorted lists

Write merge_sorted(a, b): a and b are the first nodes of two singly linked lists, each sorted from smallest to largest (repeats allowed; either may be None). Splice them into one sorted list and return its first node. Each ListNode has val and next.

Re-link the nodes you were given instead of creating new ones: O(1) extra memory.

The tests call the provided run_merge_sorted(a_values, b_values), which builds both lists from a_values and b_values and returns the values of the list you return.

  • run_merge_sorted([1,3,5], [2,4,6]) → [1,2,3,4,5,6]
  • run_merge_sorted([1,2,4], [1,3,4]) → [1,1,2,3,4,4]
  • run_merge_sorted([], [0]) → [0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Put a dummy node in front of the result and keep a tail pointer on its last node; with the dummy, the first pick is not a special case.

Hint 2

While both lists have nodes, attach the smaller front node to tail and advance that list. When one runs out, attach the rest of the other in one step.

Solution and why it works
pythonO(n + m) · O(1)
# --- your code ---
def merge_sorted(a: "ListNode | None", b: "ListNode | None") -> "ListNode | None":
    dummy = tail = ListNode()            # tail is the last node of the merged part
    while a is not None and b is not None:
        if a.val <= b.val:
            tail.next = a
            a = a.next
        else:
            tail.next = b
            b = b.next
        tail = tail.next
    tail.next = a if a is not None else b    # one list ran out: the rest is already sorted
    return dummy.next


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_nodes(head: ListNode | None, limit: int) -> list[ListNode]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the result has more nodes than the input: is there a cycle?")
        out.append(head)
        head = head.next
    return out


def run_merge_sorted(a_values: list[int], b_values: list[int]) -> list[int]:
    a, b = build_list(a_values), build_list(b_values)
    given = to_nodes(a, len(a_values)) + to_nodes(b, len(b_values))
    merged = to_nodes(merge_sorted(a, b), len(given))
    if not {id(n) for n in merged} <= {id(n) for n in given}:
        raise ValueError("re-link the nodes you were given: the result has new nodes")
    return [n.val for n in merged]

Each step moves the smaller of the two front nodes onto tail, so the result stays sorted and every node is touched once: O(n + m) time, O(1) extra memory. The dummy node gives tail a place to start, so the first pick needs no special case; return dummy.next. When one list runs out, the other is already sorted: attach it whole. Traps: forgetting that leftover, building new nodes (O(n + m) memory), and a recursive merge, which uses O(n + m) stack.