Skip to content

Commit a20a72c

Browse files
authored
Merge pull request #973 from VaishnaviMankala19/leetcode23
Leetcode23
2 parents d7e36c8 + 72a8a93 commit a20a72c

File tree

1 file changed

+190
-0
lines changed

1 file changed

+190
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
---
2+
id: merge-k-sorted-lists
3+
title: Merge k Sorted Lists (LeetCode)
4+
sidebar_label: 0023-MergekSortedLists
5+
description: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
6+
---
7+
8+
## Problem Description
9+
10+
| Problem Statement | Solution Link | LeetCode Profile |
11+
| :---------------- | :------------ | :--------------- |
12+
| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Merge k Sorted Lists Solution on LeetCode](https://leetcode.com/problems/merge-k-sorted-lists/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) |
13+
14+
## Problem Description
15+
16+
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
17+
18+
Merge all the linked-lists into one sorted linked-list and return it.
19+
20+
### Examples
21+
22+
#### Example 1
23+
24+
- **Input:** `lists = [[1,4,5],[1,3,4],[2,6]]`
25+
- **Output:** `[1,1,2,3,4,4,5,6]`
26+
- **Explanation:** The linked-lists are:
27+
`[
28+
1->4->5,
29+
1->3->4,
30+
2->6
31+
]`
32+
merging them into one sorted list:
33+
`1->1->2->3->4->4->5->6`
34+
35+
#### Example 2
36+
37+
- **Input:** `lists = []`
38+
- **Output:** `[]`
39+
40+
#### Example 3
41+
42+
- **Input:** `lists = [[]]`
43+
- **Output:** `[]`
44+
45+
### Constraints
46+
47+
- `k == lists.length`
48+
- $0 <= k <= 10^4$
49+
- $0 <= lists[i].length <= 500$
50+
- $-10^4 <= lists[i][j] <= 10^4$
51+
- `lists[i]` is sorted in ascending order.
52+
- The sum of `lists[i].length` will not exceed `10^4`.
53+
54+
### Approach
55+
56+
To merge `k` sorted linked lists, we can use a min-heap (priority queue) to efficiently get the smallest node among the current heads of the lists. This ensures that we always add the smallest element to the merged list.
57+
58+
1. **Initialize the Min-Heap:**
59+
- Add the first node of each linked list to the heap.
60+
61+
2. **Build the Merged List:**
62+
- Extract the smallest node from the heap and add it to the merged list.
63+
- If the extracted node has a next node, add it to the heap.
64+
- Repeat until the heap is empty.
65+
66+
### Solution Code
67+
68+
#### Python
69+
70+
```python
71+
from heapq import heappop, heappush
72+
73+
class ListNode:
74+
def __init__(self, val=0, next=None):
75+
self.val = val
76+
self.next = next
77+
78+
def __lt__(self, other):
79+
return self.val < other.val
80+
81+
class Solution:
82+
def mergeKLists(self, lists):
83+
min_heap = []
84+
85+
# Initialize the heap
86+
for l in lists:
87+
if l:
88+
heappush(min_heap, l)
89+
90+
dummy = ListNode()
91+
current = dummy
92+
93+
# Extract the minimum node from the heap
94+
while min_heap:
95+
node = heappop(min_heap)
96+
current.next = node
97+
current = current.next
98+
if node.next:
99+
heappush(min_heap, node.next)
100+
101+
return dummy.next
102+
```
103+
#### Java
104+
105+
```java
106+
import java.util.PriorityQueue;
107+
108+
class ListNode {
109+
int val;
110+
ListNode next;
111+
ListNode(int x) { val = x; }
112+
}
113+
114+
class Solution {
115+
public ListNode mergeKLists(ListNode[] lists) {
116+
PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);
117+
118+
for (ListNode list : lists) {
119+
if (list != null) {
120+
minHeap.offer(list);
121+
}
122+
}
123+
124+
ListNode dummy = new ListNode(0);
125+
ListNode current = dummy;
126+
127+
while (!minHeap.isEmpty()) {
128+
ListNode node = minHeap.poll();
129+
current.next = node;
130+
current = current.next;
131+
if (node.next != null) {
132+
minHeap.offer(node.next);
133+
}
134+
}
135+
136+
return dummy.next;
137+
}
138+
}
139+
140+
```
141+
142+
#### C++
143+
144+
``` c++
145+
#include <queue>
146+
147+
struct ListNode {
148+
int val;
149+
ListNode *next;
150+
ListNode(int x) : val(x), next(nullptr) {}
151+
};
152+
153+
struct compare {
154+
bool operator()(ListNode* a, ListNode* b) {
155+
return a->val > b->val;
156+
}
157+
};
158+
159+
class Solution {
160+
public:
161+
ListNode* mergeKLists(vector<ListNode*>& lists) {
162+
priority_queue<ListNode*, vector<ListNode*>, compare> minHeap;
163+
164+
for (ListNode* list : lists) {
165+
if (list != nullptr) {
166+
minHeap.push(list);
167+
}
168+
}
169+
170+
ListNode dummy(0);
171+
ListNode* current = &dummy;
172+
173+
while (!minHeap.empty()) {
174+
ListNode* node = minHeap.top();
175+
minHeap.pop();
176+
current->next = node;
177+
current = current->next;
178+
if (node->next != nullptr) {
179+
minHeap.push(node->next);
180+
}
181+
}
182+
183+
return dummy.next;
184+
}
185+
};
186+
187+
```
188+
189+
#### Conclusion
190+
The above solutions effectively merge k sorted linked lists into a single sorted list using a min-heap. This approach ensures that the smallest element is always added next to the merged list, maintaining sorted order. This solution efficiently handles edge cases and returns the correct merged list for various input configurations.

0 commit comments

Comments
 (0)