Merge K Sorted Lists17 Mar 2025 | 8 min read Problem Statement: In this statement we have a List of Linked Lists where each and every linked list is sorted in ascending order, You need to merge the linked lists in such a way that the obtained list should be in non-decreasing order (ascending order) Sample Test Cases: Note: Before getting into the article, try coming up with an approach first for having better understanding.Method 1: Brute Force Approach A straightforward approach involves initializing the result with the first list and then iterating through the remaining lists. For each node in the current list, insert it into the result in a sorted manner. Below is the Java Implementation of the above mentioned approach public class MergeKSortedLists { // Node class for linked list static class ListNode { int data; ListNode next; public ListNode(int data) { this.data = data; this.next = null; } } static void printList(ListNode node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Main function that takes an array of lists and generates the sorted output static ListNode mergeKLists(ListNode[] lists, int last) { for (int i = 1; i <= last; i++) { while (true) { ListNode head0 = lists[0], headI = lists[i]; if (headI == null) break; if (head0.data >= headI.data) { lists[i] = headI.next; headI.next = head0; lists[0] = headI; } else { while (head0.next != null) { if (head0.next.data >= headI.data) { lists[i] = headI.next; headI.next = head0.next; head0.next = headI; break; } head0 = head0.next; if (head0.next == null) { lists[i] = headI.next; headI.next = null; head0.next = headI; head0.next.next = null; break; } } } } } return lists[0]; } // Utility function to create a new node static ListNode newNode(int data) { return new ListNode(data); } // Driver program to test above functions public static void main(String[] args) { // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // Array of pointers storing the head nodes of the linked lists ListNode[] lists = new ListNode[k]; lists[0] = newNode(1); lists[0].next = newNode(3); lists[0].next.next = newNode(5); lists[0].next.next.next = newNode(7); lists[1] = newNode(2); lists[1].next = newNode(4); lists[1].next.next = newNode(6); lists[1].next.next.next = newNode(8); lists[2] = newNode(0); lists[2].next = newNode(9); lists[2].next.next = newNode(10); lists[2].next.next.next = newNode(11); // Merge all lists ListNode head = mergeKLists(lists, k - 1); // Print the merged list printList(head); } }Output: ![]() Complexity Analysis: Time complexity: O(n^k-1), because we are traversing n times on each of the K lists. Space Complexity: O(1). Method 2: Using Min Heap: This solution employs the Min Heap approach. Initially, a Min Heap is constructed by inserting the first element from each of the K Linked Lists. The algorithm proceeds by extracting the root element from the Min Heap and appending it to the output Linked List. Subsequently, the next element from the Linked List associated with the extracted element is inserted into the Min Heap. This process iterates until there are no elements remaining in the Min Heap, ultimately yielding the desired result. Algorithm:
Note: The Min Heap ensures that the smallest element among the remaining candidates is always at the root, facilitating the construction of the sorted merged list. The algorithm terminates when there are no more elements in the Min Heap, indicating that all linked lists have been processed.Java Implementation of the above mentioned approach Explanation: Output: ![]() Complexity Analysis: Time Complexity: O(n*k*logk) Space Complexity: O(k) Method 3: Using Divide & Conquer Approach: The approach involves iteratively pairing up sorted lists, halving the total number of lists at each iteration, until all the lists are merged. Follow these steps to solve the problem:
Java implementation of the above mentioned approach Output: ![]() Complexity Analysis: Time Complexity: O(n*k^2) Space Complexity: O(n) Next TopicTriplet sum closest to given number |
Problem Statement We are provided with an array of digits, and our task is to determine the largest multiple of three that can be created by concatenating some or all of these digits in any order. If it's not possible to form a valid multiple of three,...
12 min read
This article will teach us to find the kth largest element in an unsorted array. There are different ways to find the solution to the given problem. The best possible practices are discussed below: Problem - Consider an unsorted array with N number of elements. A number...
26 min read
Introduction to Binary Search Trees (BSTs) A hierarchical data structure called a binary search tree is employed for effective data storage and retrieval. It is made up of nodes and edges, where each node houses a value. Anatomy of a Binary Search Tree A BST consists of nodes with...
4 min read
? In this article, we will understand the sparse matrices and their types in detail. What do you mean by Sparse Matrices? A wide range of numerical problems in real-life applications such as engineering, scientific, computing, and economic use huge matrices. These matrices often contain many zero elements, and...
7 min read
Find Greater Element in Binary Tree Binary trees play a crucial role in depicting the relationships between the elements. A binary tree comprises nodes, and each node can have at most two nodes. It is also responsible for making a powerful way of storing, managing, and...
5 min read
Advanced data structures are one of the most important disciplines of data science since they are used for storing, organizing, managing data and information to make it more efficient, easier to access, and modify. They are the foundation for designing and developing efficient and effective software...
12 min read
In 1962, GM Adelson-Velsky and EM Landis created the AVL Tree. To honors the people who created it, the tree is known as AVL. The definition of an AVL tree is a height-balanced binary search tree in which each node has a balance factor that is determined...
6 min read
Various data structures in computer science aid in the organization of data in various forms. Trees are popular abstract data structures that simulate a hierarchical tree structure. A tree typically has a root value and subtrees formed by child nodes from parent nodes. Non-linear data structures...
6 min read
What does the binary tree's lowest common ancestor represent? The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we are looking for the LCA. As a result,...
7 min read
Data structures must also be able to be transformed into a format that can be stored and later reconstructed. A data structure is transformed into a series of bits through the process of serialization. The process of recreating the data structure from the serialized sequence is...
9 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India