Problem overview
mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It returns the head of one sorted list that holds all the nodes of both. An empty list is represented by null, so either argument, or both, can be null.
The lesson provides the node class: ListNode has an Int field named val and a nullable next. Because val is a Kotlin keyword, the field is written with backticks, node.`val`.
For list1 = [1,2,4] and list2 = [1,3,4] the result is [1, 1, 2, 3, 4, 4]. With [] and [0] it is [0], and with [-4,10,12] and [-7,0] it is [-7, -4, 0, 10, 12]. The statement asks for the nodes to be spliced together, not copied: the answer is built by re-linking the nodes that already exist, so the extra space is O(1).
Approach
Both lists are sorted, so the smallest value not yet used is always at the front of one of them. Compare the two front nodes, attach the smaller one to the end of the merged list, and move that list's head forward. Repeat until one list runs out. The rest of the other list is already sorted and every value in it is at least as large as what was merged, so it can be attached in one step.
The awkward part is the first node. The merged list is empty at the start, so there is no node whose next could point at the first choice. A dummy node removes that special case: it sits in front of the merged list, every real node is attached after the current last node in the same way, and the answer is dummy.next.
A recursive merge is shorter to write, but it makes one call per node, and the lists can hold 10,000 nodes each. A loop uses no call stack, and that is what this lesson does. The loop runs once per attached node, so the time is O(n + m) for lists of length n and m.
Step by step
- Make mutable copies of the parameters. Kotlin parameters are read-only, but the loop has to move both heads forward.
var list1 = list1creates a variable with the same name that hides the parameter. - Create the dummy node with
ListNode()and keep it in aval. It never changes, so it can't be lost, and at the end it still points at the front of the merged list. - Create
tail, avarthat starts ondummy. It always stands on the last node of the merged list. - Loop while both lists have nodes. Inside the loop Kotlin knows that
list1andlist2are notnull(a smart cast, possible because they are local variables), so their fields can be read directly. - Compare the front values with
<=. On a tie the node fromlist1goes first, so equal values keep their order. - Attach and advance. In the first branch set
tail.nexttolist1, then movelist1to itsnext. Theelsebranch does the same with the lists swapped. - Move
tailonto the node just attached. Both branches end the same way, so this line comes after theif/else. Sincenexthas the typeListNode?,!!tells the compiler it is notnullhere. - Attach the leftovers. When the loop ends, at least one list is empty.
if (list1 != null) list1 else list2is an expression, so it can be assigned straight totail.next. If both lists are used up, it assignsnull, which correctly ends the list. - Return
dummy.next, the first real node. If both inputs were empty, that isnull, an empty list.
The solution in Kotlin
class Solution {
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
var list1 = list1
var list2 = list2
val dummy = ListNode()
var tail = dummy
while (list1 != null && list2 != null) {
if (list1.`val` <= list2.`val`) {
tail.next = list1
list1 = list1.next
} else {
tail.next = list2
list2 = list2.next
}
tail = tail.next!!
}
tail.next = if (list1 != null) list1 else list2
return dummy.next
}
}
Some Kotlin details in this code:
var list1 = list1compiles because the new local variable shadows the parameter. After that line, every use oflist1in the function refers to the variable.`val`in backticks lets a keyword be used as a name. Without themlist1.valdoesn't compile.tail.next!!throws an exception ifnextisnull. It can't be here, because the line above, in one of the two branches, just assigned a non-null node.- Splicing reuses the original
ListNodeobjects. After merging[1,2,4]and[1,3,4], the returned head is the first node oflist1itself (===compares references and givestrue), and itsnextis the first node oflist2. That also means the input lists are changed: after the call, the old heads are parts of the merged list.
Complexity
Time: O(n + m). Each loop turn attaches one node and moves one head forward, so the loop runs at most n + m times. Attaching the leftovers is a single assignment.
Space: O(1). The function creates one extra node, the dummy, and a few variables. The merged list is made of the nodes that were already there.
Edge cases and common mistakes
- Empty lists. With
[]and[0]the loop never runs andtail.nextbecomeslist2, so the result is[0]. With two empty lists the result isnull. - One list much shorter. With
[-4,10,12]and[-7,0], the values-7,-4and0are attached one by one, then10 -> 12follows without any more comparisons. - Ties. Using
<instead of<=still gives a sorted list, but equal values fromlist2would come first. Using<=keepslist1's node first, as in the example. - Forgetting to advance
tail. Withouttail = tail.next!!each new node overwrites the previous one's place, and the merged list keeps only the last node attached. - Returning
dummy. The dummy is not part of the answer, so returndummy.next.
Testing
Run the function on these inputs and compare:
[1, 2, 4] + [1, 3, 4] -> [1, 1, 2, 3, 4, 4]
[] + [0] -> [0]
[-4, 10, 12] + [-7, 0] -> [-7, -4, 0, 10, 12]
[] + [] -> []
