Merge Two Sorted Linked Lists And Remove Duplicates
Merge two sorted linked lists into one sorted list in which each value appears once.
Given the heads of two linked lists, list1list2
Example 1
Output: [1, 2, 3, 4]
Example 2
Output: [1, 2]
Explanation: repeats can come from within one list as well as from both lists.
Example 3
Output: [0]
The Idea
Picture two stacks of numbered cards, each sorted with the smallest on top, and you want one sorted pile with every number only once. You would look at the top card of both stacks, take the smaller one, and repeat until both stacks are empty.
Here the stacks are linked lists. A linked list is a chain of nodes: each node holds a value and a pointer, called nextnextnull
Take Example 2: list1list2list1
So how do we spot a repeat while merging? Checking each new node against every node kept so far would work, but that is a search for every node. Look at the picture below.
The row labelled node shows the five nodes in the order the merge takes them. Under each one, the row labelled last kept value shows the value of the node most recently put into the result. The second 1 meets a last kept value of 1, so it is skipped. The first 2 meets 1, so it is kept, and the two 2s from list2
Because the merge hands out nodes in sorted order, all copies of a value arrive one right after another. So a node is a repeat exactly when its value equals the last kept value, and one comparison per node is enough.
Solution Approach
One simple way merges first and removes the repeats afterwards; doing both in a single pass means settling three things: how to take the nodes in sorted order, how to compare each node with the last kept one, and how to end the result list.
Merging first, then removing repeats
Can known pieces do the job? Merge the lists as in
Taking the nodes in sorted order
Which node comes next? The smaller of the two front nodes. The variables list1list2nextlist1
A plain merge attaches whatever is left of the longer list in one step. Here the loop keeps going until both lists are empty, because the leftover nodes can be repeats too. With list1 = [3, 3]list2 = [3]list2list1
Comparing with the last kept node
Where does the last kept value come from? The result grows by attaching nodes at its end, so the code keeps a pointer, tailtail.val
The very first node has nothing to compare with. An extra node placed before the result's first real node, called a dummy node, handles that: tailtaildummy.next
Ending the result list
What happens to the skipped nodes? They are never attached, but every kept node still has its old nextnext
Take list1 = [2, 3, 3]list2 = [1]list1nexttail.next = null
Java Solution
The method mergeWithoutDuplicates
- First, create the dummy node
and pointdummy at it.tail always marks the last node of the result.tail - Loop while
orlist1 still has nodes. Inside, put the smaller front node intolist2 : the one fromsmaller whenlist1 is empty orlist2 's front value is smaller or equal, otherwise the one fromlist1 . Move that list's marker to its next node.list2 - If
is stilltail , ordummy differs fromtail.val , attach the node withsmaller.val and movetail.next = smaller to it. Otherwise leavetail out.smaller - After the loop, set
so the result does not run on into a skipped node, and returntail.next = null .dummy.next
The class also has a small ListNodebuildshow[1, 2]main[3, 3][3][2, 3, 3][1]
public class MergeTwoSortedListsAndRemoveDuplicates {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode mergeWithoutDuplicates(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (list1 != null || list2 != null) {
ListNode smaller;
if (list2 == null || (list1 != null && list1.val <= list2.val)) {
smaller = list1;
list1 = list1.next;
} else {
smaller = list2;
list2 = list2.next;
}
if (tail == dummy || tail.val != smaller.val) { // a new value: keep it
tail.next = smaller;
tail = smaller;
}
}
tail.next = null; // the last kept node may still point at a skipped node
return dummy.next;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode node = head; node != null; node = node.next) {
sb.append(node.val).append(node.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(mergeWithoutDuplicates(build(1, 2, 4), build(1, 3, 4))));
System.out.println(show(mergeWithoutDuplicates(build(1, 1, 2), build(2, 2))));
System.out.println(show(mergeWithoutDuplicates(build(), build(0))));
System.out.println(show(mergeWithoutDuplicates(build(3, 3), build(3))));
System.out.println(show(mergeWithoutDuplicates(build(2, 3, 3), build(1))));
System.out.println(show(mergeWithoutDuplicates(build(), build())));
}
}
Running it prints:
[1, 2, 3, 4]
[1, 2]
[0]
[3]
[1, 2, 3]
[]
The second line, [1, 2][3]list2list1
The fifth line, [1, 2, 3]tail.next = null[1, 2, 3, 3][3, 3][3][3, 3][]dummy.nextnull
The original implementation and its tests are on GitHub:
Complexity
Each pass of the loop takes exactly one node from one of the two lists, whether that node is kept or skipped.
- Time: O(m + n), for lists of m and n nodes: the loop runs once per node of either list, and each pass does one comparison of front values and one comparison with the last kept value.
- Space: O(1). The only new node is
. Kept nodes are relinked by changing theirdummy pointers, and skipped nodes are simply never attached.next