Merge Two Sorted Lists
Problem
Two sorted arrays are given (each as a count and the values). Build a linked list from each, then merge the two lists into one sorted list by relinking the nodes. Print the merged values.
Constraints
- 1 <= n, m <= 10^5
- Both arrays are sorted
Examples
Input
3 1 2 4 3 1 3 4
Output
1 1 2 3 4 4
Solutions
Like the merge step of merge sort, but we relink existing nodes instead of copying. A dummy node in front removes the special case for the first node.
/*
* Problem : Merge two sorted lists.
* Input : Two counts and two arrays.
* Output : The merged list.
* Approach: Dummy head node.
* Time : O(n + m)
* Space : O(1) extra
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// Step 1: A node holds one value and a link to the next node. The last node links to null.
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
}
// This method builds a linked list from an array and returns the first node.
static Node build(int[] values) {
Node head = null;
Node tail = null;
for (int value : values) {
Node node = new Node(value);
if (head == null) {
head = node;
} else {
tail.next = node;
}
tail = node;
}
return head;
}
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a, int[] b) {
// Step 2: Build two linked lists.
Node headA = build(a);
Node headB = build(b);
// Step 3: dummy is a helper node in front of the result. This avoids special code for the first node.
Node dummy = new Node(0);
Node tail = dummy;
// Step 4: Always take the smaller front node of the two lists. Use <= so that equal values keep their order.
while (headA != null && headB != null) {
if (headA.value <= headB.value) {
tail.next = headA;
headA = headA.next;
} else {
tail.next = headB;
headB = headB.next;
}
tail = tail.next;
}
// Step 5: One list is empty now. Link the rest of the other list.
tail.next = (headA != null) ? headA : headB;
// Step 6: Copy the values to an array for printing.
int[] result = new int[a.length + b.length];
int index = 0;
for (Node node = dummy.next; node != null; node = node.next) {
result[index++] = node.value;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int sizeB = scanner.nextInt();
int[] b = new int[sizeB];
for (int i = 0; i < sizeB; i++) {
b[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a, b)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Why is a dummy head node useful?