# Merge k Sorted Lists Leetcode Solution

Difficulty Level Hard
Divide and Conquer Heap Linked-List Shopee tiktok TuSimple Walmart Global techViews 4812

## Problem Statement

The Merge k Sorted Lists LeetCode Solution – “Merge k Sorted Lists” states that given the array of k linked lists, where each linked list has its values sorted in ascending order. We need to merge all the k-linked lists into one single linked list and return the head of the linked list.

## Example:

`Input:  lists = [[1,4,5],[1,3,4],[2,6]]`
`Output: [1,1,2,3,4,4,5,6]`

Explanation:

• Consider all values in ascending order: [1, 1, 2, 3, 4, 4, 5, 6].
• We need to form a linked list with the above values.
`Input:  lists = []`
`Output: []`

Explanation:

• The input array is empty, return the null pointer as the head of the linked list.

## Approach

### Idea:

1. The main idea to solve this problem is to use Priority Queue.
2. Iterate in the array of linked lists and store all pairs {values, head pointers} in the min-heap.
3.  Each time, pop out the node with the minimum value from the min-heap and make it the next node of the newly formed linked list.
4. Also, check if the popped node has the next node, then insert the pair {value, next node} in the min-heap again.
5. Above mentioned process, results in the formation of a new linked list with all the values sorted in ascending order since every time, we’re extracting the node with minimum value and making it the next node of the new linked list.
6. Finally, we have merged k linked lists.

## Code

### Merge k Sorted Lists Leetcode C++ Solution:

```class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()){
return nullptr;
}
ListNode* dummy = new ListNode(0);
priority_queue<pair<int,ListNode*>,vector<pair<int,ListNode*>>,greater<pair<int,ListNode*>>> pq;
for(auto& node:lists){
if(node!=nullptr){
pq.push({node->val,node});
}
}
while(!pq.empty()){
ListNode* node = pq.top().second;
pq.pop();
if(node->next!=nullptr){
pq.push({node->next->val,node->next});
}
dummy->next = node;
dummy = node;
}
}
};```

### Merge k Sorted Lists Leetcode Java Solution:

```class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0){
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length, (a,b)-> a.val-b.val);
for(ListNode node:lists){
if(node!=null){
}
}
ListNode dummy = new ListNode(0);
while(!pq.isEmpty()){
ListNode node = pq.poll();
if(node.next!=null){
}
dummy.next = node;
dummy = node;
}
}
}```

## Complexity Analysis for Merge k Sorted Lists Leetcode Solution

### Time Complexity

The time complexity of the above code is O(NKlogK). Each node is pushed into the min-heap once and there are total at most N*K nodes in the given array of linked lists, where N = maximum number of nodes in a single linked list and K = size of the array of the linked list.

### Space Complexity

The space complexity of the above code is O(K) since we’re using a min-heap of maximum size k.
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://tutorialcup.com/leetcode-solutions/merge-k-sorted-lists-leetcode-solution.htm", "fetch_time": 1726089231000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-38/segments/1725700651400.96/warc/CC-MAIN-20240911183926-20240911213926-00472.warc.gz", "warc_record_offset": 567348001, "warc_record_length": 19316, "token_count": 773, "char_count": 3010, "score": 4.03125, "int_score": 4, "crawl": "CC-MAIN-2024-38", "snapshot_type": "latest", "language": "en", "language_score": 0.6556428670883179, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00015-of-00064.parquet"}