Java Program To Merge K Sorted Linked Lists - Set 1
Last Updated :
03 Jan, 2022
Given K sorted linked lists of size N each, merge them and print the sorted output.
Examples:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Input: k = 3, n = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Method 1 (Simple):
Approach:
A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way.
Java
// Java program to merge k sorted
// linked lists of size n each
import java.io.*;
// A Linked List node
class Node
{
int data;
Node next;
// Utility function to create
// a new node.
Node(int key)
{
data = key;
next = null;
}
}
class GFG
{
static Node head;
static Node temp;
/* Function to print nodes in
a given linked list */
static void printList(Node node)
{
while(node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
// The main function that takes an array
// of lists arr[0..last] and generates
// the sorted output
static Node mergeKLists(Node arr[],
int last)
{
// Traverse form second list to last
for (int i = 1; i <= last; i++)
{
while(true)
{
// head of both the lists,
// 0 and ith list.
Node head_0 = arr[0];
Node head_i = arr[i];
// Break if list ended
if (head_i == null)
break;
// Smaller than first element
if(head_0.data >= head_i.data)
{
arr[i] = head_i.next;
head_i.next = head_0;
arr[0] = head_i;
}
else
{
// Traverse the first list
while (head_0.next != null)
{
// Smaller than next element
if (head_0.next.data >= head_i.data)
{
arr[i] = head_i.next;
head_i.next = head_0.next;
head_0.next = head_i;
break;
}
// Go to next node
head_0 = head_0.next;
// If last node
if (head_0.next == null)
{
arr[i] = head_i.next;
head_i.next = null;
head_0.next = head_i;
head_0.next.next = null;
break;
}
}
}
}
}
return arr[0];
}
// Driver code
public static void main (String[] args)
{
// Number of linked lists
int k = 3;
// Number of elements in each list
int n = 4;
// an array of pointers storing the
// head nodes of the linked lists
Node[] arr = new Node[k];
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
// Merge all lists
head = mergeKLists(arr, k - 1);
printList(head);
}
}
// This code is contributed by avanitrachhadiya2155
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
- Time complexity: O(nk2)
- Auxiliary Space: O(1).
As no extra space is required.
Method 2: Min Heap.
A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k)
Method 3: Divide and Conquer.
In this post, Divide and Conquer approach is discussed. This approach doesn't require extra space for heap and works in O(nk Log k)
It is known that merging of two linked lists can be done in O(n) time and O(n) space.
- The idea is to pair up K lists and merge each pair in linear time using O(n) space.
- After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
- Repeat the procedure until we have only one list left.
Below is the implementation of the above idea.
Java
// Java program to merge k sorted
// linked lists of size n each
public class MergeKSortedLists
{
/* Takes two lists sorted in increasing order,
and merge their nodes together to make one
big sorted list. Below function takes O(Log n)
extra space for recursive calls, but it can be
easily modified to work with same time and
O(1) extra space */
public static Node SortedMerge(Node a, Node b)
{
Node result = null;
// Base cases
if (a == null)
return b;
else if (b == null)
return a;
// Pick either a or b, and recur
if (a.data <= b.data)
{
result = a;
result.next = SortedMerge(a.next, b);
}
else
{
result = b;
result.next = SortedMerge(a, b.next);
}
return result;
}
// The main function that takes an array
// of lists arr[0..last] and generates
// the sorted output
public static Node mergeKLists(Node arr[],
int last)
{
// Repeat until only one list is left
while (last != 0)
{
int i = 0, j = last;
// (i, j) forms a pair
while (i < j)
{
// Merge List i with List j and
// store merged list in List i
arr[i] = SortedMerge(arr[i], arr[j]);
// consider next pair
i++;
j--;
// If all pairs are merged, update last
if (i >= j)
last = j;
}
}
return arr[0];
}
/* Function to print nodes in a
given linked list */
public static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String args[])
{
// Number of linked lists
int k = 3;
// Number of elements in each list
int n = 4;
// An array of pointers storing the
// head nodes of the linked lists
Node arr[] = new Node[k];
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
// Merge all lists
Node head = mergeKLists(arr, k - 1);
printList(head);
}
}
class Node
{
int data;
Node next;
Node(int data)
{
this.data = data;
}
}
// This code is contributed by Gaurav Tiwari
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists.
- Time Complexity: O(N*log k) or O(n*k*log k)
As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements. - Auxiliary Space: O(N) or O(n*k)
Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.
Please refer complete article on
Merge K sorted linked lists | Set 1 for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read