Problem overview
mergeTwoLists(list1, list2) receives the heads of two singly linked lists, each sorted in ascending order, and returns the head of one sorted list that contains all of their nodes. Either list can be empty, and an empty list is represented by null.
The lesson provides the ListNode constructor: each node has a val (default 0) and a next (default null). The merged list has to be built by linking the existing nodes, not by creating copies.
For list1 = [1, 2, 4] and list2 = [1, 3, 4] the result is [1, 1, 2, 3, 4, 4]. When two front values are equal, the node from list1 goes first, so equal values keep their original order.
Approach: always take the smaller front node
Because both lists are sorted, the smallest value not yet used is always one of the two front nodes. So the merge repeats one decision: compare the fronts, attach the smaller node to the end of the merged list, and move that list forward. This is the merge step of merge sort.
The statement asks for O(n + m) time and O(1) extra space, where n and m are the lengths of the lists. Each node is attached once, so the time is linear. No node is created except one placeholder, so the extra space is constant.
Two design choices matter:
- A dummy node. The first node of the merged list would need special handling, because there is no previous node to attach it to. A placeholder node in front removes that case: every node is attached after the current last node in the same way, and the answer is the node after the placeholder.
- A loop instead of recursion. A recursive merge goes one call deeper for every node. With up to 10,000 nodes in each list, that can run out of call stack. The loop uses no extra stack.
Step by step
- Create the placeholder.
new ListNode()gives a node withval0 andnextnull. It is stored in aconst, because the namedummyalways refers to this same node. - Create
tailwithlet. It points at the last node of the merged list, which for now is the placeholder. It will move, so it can't be aconst. - Loop while both lists have nodes. Compare with
!== null. Once one list is empty there is nothing left to compare. - Compare the fronts with
list1.val <= list2.val. Using<=rather than<sends ties tolist1. - Attach the smaller node by setting
tail.nextto it. This links the existing node itself. - Advance that list to its next node, since the front node now belongs to the merged list.
- Handle the other case with an
elsebranch that mirrors the first one forlist2. - Advance
list2inside theelse. - Move
tailto the node just attached. Both branches attach attail.next, so this one line comes after theif/else. - Attach the leftovers in one step. After the loop at least one list is empty. The remaining nodes are already sorted and none is smaller than what has been merged, so one assignment links the whole rest.
- Return
dummy.next, the first real node. The placeholder isn't part of the answer.
The solution in JavaScript
class Solution {
mergeTwoLists(list1, list2) {
const dummy = new ListNode();
let 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 = list1 !== null ? list1 : list2;
return dummy.next;
}
}
The JavaScript details worth a look:
constprotects the name, not the object.dummycan't be reassigned, butdummy.nextcan be changed freely.tailis reassigned on every pass, so it useslet.- Parameters are ordinary local variables. The loop reassigns
list1andlist2. That changes only the function's own variables, not the caller's. The nodes themselves are shared, though: theirnextfields really are changed. !== null. Empty lists arenull, so comparing with!==is exact. A node object is always truthy, sowhile (list1 && list2)would also work.- The conditional operator.
list1 !== null ? list1 : list2giveslist1if it still has nodes andlist2otherwise. If both are used up, it giveslist2, which isnull, and that ends the merged list correctly.
After a merge, the input lists are no longer separate. With list1 = [1, 3] and list2 = [1], the returned head is the original first node of list1, and its next is the original list2 node.
Complexity
Time: O(n + m). Each pass of the loop attaches one node and moves one pointer forward, so the loop runs at most n + m times. The final attachment is a single assignment.
Space: O(1). The function creates one placeholder node and uses a few variables. The merged list reuses the input nodes.
Edge cases and common mistakes
- Empty lists. With
list1 = nullandlist2 = [0]the loop never runs,tail.nextbecomeslist2, and the result is[0]. With both empty,dummy.nextis stillnull. - One list much longer. For
[-4, 10, 12]and[-7, 0],list2runs out after-7,-4and0are placed. The rest,10 -> 12, is attached without more comparisons. - Forgetting to move
tail. Every new node would then replace the previous one attail.next, and the merged list would lose nodes. - Forgetting the leftovers. Without the assignment after the loop, the rest of the longer list is dropped.
- Returning
dummy. That adds a stray0at the front of the answer. - Using
<for ties. The result has the same values, but equal values fromlist2would come before those oflist1, which breaks the order the lesson expects. - Recursion. It's shorter to write, but its depth grows with the number of nodes, so the loop is the safer choice for long lists.
Testing
Outputs of the solution, with the lists written as arrays:
[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].
