Problem overview
The method mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It must return the head of one sorted list that contains all the nodes of both. The nodes are spliced together: the existing nodes are re-linked, and no new ones are created for the result. Either list can be empty, or both, and the head of an empty list is None.
The lesson provides the ListNode class. A node has a val and a next pointer, and ListNode() with no argument makes a node whose val is 0 and whose next is None.
With list1 = [1, 2, 4] and list2 = [1, 3, 4], the merged list is [1, 1, 2, 3, 4, 4]. With list1 = [-4, 10, 12] and list2 = [-7, 0] it is [-7, -4, 0, 10, 12]: once list2 is used up, the rest of list1 follows unchanged.
Approach: always take the smaller front node
Both lists are sorted, so the smallest value not yet placed is always at the front of one of them. Compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each node is looked at once, so the time is O(n + m) for lists of lengths n and m. Because nodes are re-linked rather than copied, the extra space is O(1).
The awkward part is the very first node. The merged list starts empty, so attaching the first node would need a special case. The usual fix is a dummy node: a placeholder in front of the merged list. A variable tail starts on the dummy and always points to the last node of the merged list. Every node, including the first, is attached the same way, as tail.next. At the end, the real list is dummy.next.
A recursive merge is shorter to write, but it makes one call per node. With up to 10,000 nodes in each list, the call stack runs out: on 20,000 nodes the recursive version raises RecursionError under Python's default limit. The loop has no such limit.
Step by step
- Create the dummy node with
ListNode()and store it indummy. Its value is never used. - Point
tailatdummy. The merged list is just the dummy for now, so it is also its last node. - Loop while both lists have nodes.
Noneis falsy, sowhile list1 and list2:stops as soon as either list runs out. - Compare the front values with
list1.val <= list2.val. Using<=sends ties tolist1, so equal values keep list1's before list2's. - Attach
list1's front node:tail.next = list1. This links the node itself. - Advance
list1tolist1.next. The attached node now belongs to the merged list. - Otherwise attach
list2's front node in anelsebranch, mirroring the first branch. - Advance
list2tolist2.next. - Move
tailforward totail.next, after theif/else. Both branches attached a node, so this line is shared. - Attach the leftover nodes in one step. When the loop ends, at least one list is empty. The other is already sorted, and none of its values is smaller than what was merged, so it is linked on as it is.
- Return
dummy.next, the first real node. If both inputs were empty it isNone.
The solution in Python
class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
tail.next = list1 if list1 else list2
return dummy.next
Python details worth a look:
- Truthiness of nodes. A node is an ordinary object, so it counts as true, and
Nonecounts as false. That is whywhile list1 and list2works without comparing toNone. A node whosevalis 0 is still true, because the test applies to the node and not to its value. - Variables are names for nodes.
list1 = list1.nextonly changes which node the namelist1refers to. The node that was attached keeps its ownnextuntil the following iteration overwrites it throughtail.next, so the lists are not damaged. - The conditional expression.
list1 if list1 else list2giveslist1when it still has nodes andlist2otherwise. When both are used up it givesNone, which correctly ends the list. - The lists are modified. The result reuses the input nodes: with
list1 = [1]andlist2 = [1], the returned head is thelist1node itself and itsnextis thelist2node.
Complexity
Time: O(n + m). Every iteration of the loop attaches one node and moves one pointer forward, so the loop runs at most n + m times. Attaching the leftover list is a single assignment.
Space: O(1). The function keeps a dummy node and the variables tail, list1 and list2, whatever the list sizes.
Edge cases and common mistakes
- An empty list. With
list1 = []andlist2 = [0]the loop never runs, the leftover step attacheslist2, and the result is[0]. With both empty the result is[]. - Returning
dummy. The dummy is a placeholder with value 0. Returning it would put an extra 0 at the front of the answer. - Forgetting to advance
tail. Each new node would overwrite the previoustail.next, and the merged list would end up with a single node. - Forgetting the leftover. After the loop one list can still have nodes, such as
10 -> 12in the second example. Without the final attachment they would be lost. - Using
<instead of<=. The result is still sorted, but ties then come fromlist2first, so equal values no longer keep the order list1 before list2. - Recursion on long lists. Python's default recursion limit is about 1,000 calls, far below the 20,000 nodes the constraints allow.
Testing
[1, 2, 4]and[1, 3, 4]give[1, 1, 2, 3, 4, 4].[]and[0]give[0].[-4, 10, 12]and[-7, 0]give[-7, -4, 0, 10, 12].[]and[]give[].[5]and[]give[5].[1, 1]and[1]give[1, 1, 1].
