Merge Two Sorted Lists
Merge two sorted linked lists into one sorted list
DSA, Easy, Linked List
Which structure or algorithm, and what does it cost.
Two linked lists a and b are each sorted from smallest to largest. Equal values may repeat. Join them into one sorted list that holds every value from both, and return it. Reuse the existing nodes by relinking them. A node has val and next. Your code gets the first node of a and of b, and returns the first node of the merged list. An empty list is null. The examples write a list as its values in order, only to keep them short.
Examples
Constraints
- 0 <= length of each list <= 50,000.
- Each value is a whole number between -1,000,000 and 1,000,000.
- Each list is already sorted from smallest to largest.
Your answer must contain
- The simple method and why it wastes the sorted input; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n + m) time and O(1) extra memory, where n and m are the two lengths.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Look at the first value of each list. Only one of them can come first in the result. Which one?
Hint 2 the approach
Repeat that comparison: take the smaller front node, attach it to the result, and move forward in the list it came from.
Hint 3 the key step
Keep a dummy node before the result and a tail that grows it. When one list runs out, attach the rest of the other.
Walkthrough
Full walkthrough brute force to best
Brute force
Copy every value from both lists into one array, sort it, and build a new list from it. Sorting costs O(m log m) for m values in total, and the array plus the new list use O(m) memory. It ignores the fact that both lists are already sorted.
Best method
Put a dummy node in front and keep a tail pointer on it. Compare the front nodes of the two lists. Link the smaller one after the tail, move the tail onto it, and step forward only in the list it came from. When one list is empty, link the rest of the other list in one move, because that rest is already sorted. The answer starts at the node after the dummy. Each step takes the smallest value that is still unused, because both lists are sorted, so the result is sorted. On a tie the code takes from a first, which keeps equal values in their input order.
Hand trace
Run on a = [2, 4, 9] and b = [1, 4, 6]. Fronts 2 and 1: take 1 from b. Result [1]. Fronts 2 and 4: take 2 from a. Result [1, 2]. Fronts 4 and 4: tie, take the 4 from a. Result [1, 2, 4]. Fronts 9 and 4: take the 4 from b. Result [1, 2, 4, 4]. Fronts 9 and 6: take 6 from b. List b is empty, so link the rest of a, which is 9. The result is [1, 2, 4, 4, 6, 9].
Code
class Node:
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
def merge_two_lists(a, b): # a and b are the first nodes of the two lists
dummy = tail = Node(0) # dummy node: no special case for the first link
while a and b:
if b.val < a.val:
tail.next, b = b, b.next
else:
tail.next, a = a, a.next
tail = tail.next
tail.next = a or b # one list is empty: link the rest of the other
return dummy.next # the first node of the merged list
# Test helper, not part of the answer: builds a list of nodes from values and reads it back.
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_values(head):
out = []
while head:
out.append(head.val)
head = head.next
return outTime and memory
O(n + m) time, because each node is linked once. O(1) extra memory: the dummy node and a few pointers. The lists are relinked, not copied.
Common mistakes
- Forgetting the leftover. When one list ends first, the rest of the other list still has to be linked in.
- Starting without a dummy node. Then the first link needs its own case, and an empty input breaks it.
- Stepping forward in both lists after one comparison. Only the list that gave the node moves on.