Javascript Program To Merge K Sorted Linked Lists Using Min Heap - Set 2
Last Updated :
03 Sep, 2024
Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as 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.
Source: Merge K sorted Linked Lists | Method 2
An efficient solution for the problem has been discussed in Method 3 of this post.
Approach: This solution is based on the MIN HEAP approach used to solve the problem 'merge k sorted arrays' which is discussed here.
MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
- Create a min-heap and insert the first element of all the 'k' linked lists.
- As long as the min-heap is not empty, perform the following steps:
- Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.
- If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.
- Return the head node address of the merged list.
Below is the implementation of the above approach:
JavaScript
// Javascript implementation to merge
// k sorted linked lists using MIN HEAP method
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to merge k sorted
// linked lists
function mergeKSortedLists(arr, k) {
let head = null, last = null;
// priority_queue 'pq' implemeted
// as min heap with the help of
// 'compare' function
let pq = [];
// Push the head nodes of all
// the k lists in 'pq'
for (let i = 0; i < k; i++)
if (arr[i] != null)
pq.push(arr[i]);
pq.sort(function (a, b) {
return a.data - b.data;
});
// loop till 'pq' is not empty
while (pq.length != 0) {
// Get the top element of 'pq'
let top = pq[0];
pq.shift();
// Check if there is a node next
// to the 'top' node in the list
// of which 'top' node is a member
if (top.next != null)
// Push the next node in 'pq'
pq.push(top.next);
// if final merged list is empty
if (head == null) {
head = top;
// Points to the last node so far
// of the final merged list
last = top;
}
else {
// Insert 'top' at the end of the
// merged list so far
last.next = top;
// Update the 'last' pointer
last = top;
}
pq.sort(function (a, b) { return a.data - b.data; });
}
// Head node of the required merged list
return head;
}
// Function to print the singly linked list
function printList(head) {
while (head != null) {
console.log(head.data);
head = head.next;
}
}
// Utility function to create a
// new node
function push(data) {
let newNode = new Node(data);
newNode.next = null;
return newNode;
}
// Driver code
// Number of linked lists
let k = 3;
// Number of elements in each list
let n = 4;
// An array of pointers storing the
// head nodes of the linked lists
let arr = new Array(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
let head = mergeKSortedLists(arr, k);
printList(head);
// This code is contributed by avanitrachhadiya2155
Output0
1
2
3
4
5
6
7
8
9
10
11
Complexity Analysis:
- Time Complexity: O(N * log k) or O(n * k * log k), where, 'N' is the total number of elements among all the linked lists, 'k' is the total number of lists, and 'n' is the size of each linked list.
Insertion and deletion operation will be performed in min-heap for all N nodes.
Insertion and deletion in a min-heap require log k time. - Auxiliary Space: O(k).
The priority queue will have atmost 'k' number of elements at any point of time, hence the additional space required for our algorithm is O(k).
Please refer complete article on Merge k sorted linked lists | Set 2 (Using Min Heap) for more details!
Similar Reads
JavaScript Linked List Programs JavaScript Linked List Programs contain a list of articles based on programming. Linked List is a linear data structure that stores data in linearly connected nodes. Linked lists store elements sequentially, but doesnât store the elements contiguously like an array. S. NoArticles1JavaScript Program
5 min read
Implementation of LinkedList in Javascript In this article, we will be implementing the LinkedList data structure in Javascript.A linked list is a linear data structure where elements are stored in nodes, each containing a value and a reference (or pointer) to the next node. It allows for efficient insertion and deletion operations.Each node
5 min read
Javascript Program For Searching An Element In A Linked List Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise.bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functio
3 min read
Javascript Program For Inserting A Node In A Linked List We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. JavaScript// Linked List Class // Head of list let head; // Node
7 min read
Javascript Program For Inserting Node In The Middle Of The Linked List Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.Examples: Input : list: 1->2->4->5 x = 3Output : 1->2->3-
4 min read
Javascript Program For Writing A Function To Delete A Linked List A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. This article focuses on writing a function to delete a linked list.Implementation: JavaScript// Javascript program to delete // a li
1 min read
Javascript Program For Deleting A Linked List Node At A Given Position Given a singly linked list and a position, delete a linked list node at the given position.Example: Input: position = 1, Linked List = 8->2->3->1->7Output: Linked List = 8->3->1->7Input: position = 0, Linked List = 8->2->3->1->7Output: Linked List = 2->3->1-
3 min read
Javascript Program For Finding Length Of A Linked List Write a function to count the number of nodes in a given singly linked list.For example, the function should return 5 for linked list 1->3->1->2->1.Iterative Solution: 1) Initialize count as 0 2) Initialize a node pointer, current = head.3) Do following while current is not NULL a) curre
3 min read
Javascript Program For Rotating A Linked List Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smal
5 min read
Javascript Program For Making Middle Node Head In A Linked List Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples:Input: 1 2 3 4 5 Output: 3 1 2 4 5Input: 1 2 3 4 5 6Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves on
3 min read