Problem overview
The method mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) receives the heads of two linked lists, each sorted in ascending order, and returns the head of one sorted list that holds all their nodes. An empty list is represented by nil, and either list, or both, may be empty. The lesson provides the ListNode class: each node has a val and an optional next, and ListNode() with no arguments makes a node with value 0 and no next node.
For list1 = [1, 2, 4] and list2 = [1, 3, 4], the method returns the list [1, 1, 2, 3, 4, 4]. For list1 = [] and list2 = [0] it returns [0]. For list1 = [-4, 10, 12] and list2 = [-7, 0] it returns [-7, -4, 0, 10, 12].
The statement asks you to splice the existing nodes together rather than create new ones, in O(n + m) time and O(1) extra space.
Approach: always take the smaller front node
Both lists are sorted, so the smallest value not yet used is always at the front of one of them. That gives a simple rule: compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each comparison places one node for good, so the loop runs at most n + m times.
When one list runs out, the other still holds nodes that are sorted and no smaller than anything merged so far. They can be attached in one move, without more comparisons.
The awkward part is the first node. The merged list is empty at the start, so there is no last node to attach to, and the code would need a special case for the first attachment. A dummy node removes it. The merged list starts as a single throwaway node, every real node is attached after the current last node in the same way, and the answer is whatever follows the dummy.
A recursive version, which merges the rest of the lists after choosing the front node, also works, but it goes one call deeper per node. With up to 20,000 nodes that can exhaust the call stack, so a loop is the safer choice.
On a tie, <= takes the node from list1 first, so equal values keep their original order. With a pair of nodes that both hold 1, the merged list starts with the node from list1, followed by the one from list2.
Step by step
- Make mutable copies of the parameters. Swift parameters are constants, and the loop has to move both heads forward.
var list1 = list1declares a new variable with the same name that hides the parameter, so the rest of the code works on the copy. - Create the dummy node with
ListNode()and store it in alet. The variable always refers to the same node, soletis enough: only the node'snextchanges. - Declare
tailwithvar, starting atdummy. It always stands on the last node of the merged list, the one the next node gets attached to. At the start the merged list is just the dummy. - Loop while both lists have nodes. Once one is empty, there is nothing left to compare.
- Compare the fronts with
list1!.val <= list2!.val. The!unwraps each optional, and the loop condition guarantees that neither isnil. - Attach the smaller node. If it is
list1's, settail.next = list1. This links the existing node itself, so no new node is created. - Advance that list with
list1 = list1!.next. The attached node now belongs to the merged list, so what remains oflist1starts after it. - Mirror both steps in the
elsebranch forlist2. - Move
tailforward withtail = tail.next!. Both branches just settail.nextto a node, so it is notnil, and one shared line after theif/elsedoes the move. - Attach the leftovers after the loop. At least one list is used up, so
tail.next = list1 != nil ? list1 : list2picks the one that still has nodes. If both are empty,list2isnil, which ends the merged list correctly. - Return
dummy.next, the first real node. The dummy itself is not part of the answer.
The solution in Swift
class Solution {
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
var list1 = list1
var list2 = list2
let dummy = ListNode()
var tail = dummy
while list1 != nil && list2 != nil {
if list1!.val <= list2!.val {
tail.next = list1
list1 = list1!.next
} else {
tail.next = list2
list2 = list2!.next
}
tail = tail.next!
}
tail.next = list1 != nil ? list1 : list2
return dummy.next
}
}
The Swift details worth a closer look:
- Shadowing a parameter. Writing
list1 = list1!.nextdirectly on the parameter fails to compile:cannot assign to value: 'list1' is a 'let' constant. The linevar list1 = list1is allowed because it creates a new variable in the function's scope. - Optionals need unwrapping.
list1.valon aListNode?is a compile error:value of optional type 'ListNode?' must be unwrapped to refer to member 'val' of wrapped base type 'ListNode'. The code uses!because the loop condition has just proved the value is notnil. Without that guarantee,!on anilcrashes the program. - Classes are reference types.
ListNodeis a class, sotail = dummymakestailrefer to the same object, not a copy. That is whytail.next = list1changes the dummy's chain, and why aletconstant fordummycan still have itsnextchanged. - The nodes are reused. After merging
[1, 3]with[2], the returned head is the very node that was the head of the first list, and itsnextis the node of the second list. Nothing is copied. - The conditional operator.
condition ? a : bgivesawhen the condition is true andbotherwise. Both sides have the typeListNode?, so the result can be assigned totail.next.
Complexity
Time: O(n + m). Each iteration of the loop attaches one node and moves one list forward, so the loop runs at most n + m times. Attaching the leftovers is a single assignment.
Space: O(1). The method creates one dummy node and a few variables. The merged list is made of the nodes that were already there.
Edge cases and common mistakes
- Empty lists. With
list1 = []andlist2 = [0]the loop never runs, and the leftover step attacheslist2, giving[0]. With both empty,dummy.nextstaysnil, which is the empty list. - One list much shorter. For
[-4, 10, 12]and[-7, 0], the loop places -7, -4 and 0, thenlist2is empty and10 -> 12is attached as it is. - Forgetting the leftovers. Without the line after the loop, everything left in the longer list is dropped.
- Returning
dummy. That includes the placeholder node with value 0 at the front of the answer. Returndummy.next. - Forgetting to advance
tail. Each attachment would overwrite the previous one, and the earlier nodes would be lost from the merged list. - Using
<instead of<=. The merged values are the same, but on ties the nodes fromlist2would come first, so equal values would no longer keep their original order.
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].
