Skip to content

Commit 9f92f6b

Browse files
committed
Solution Dijkstra-Edu#23 - Daniel/Edited - 18.03.2025
1 parent b112a43 commit 9f92f6b

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Merge K Sorted Arrays Solution
2+
3+
## Overview
4+
5+
The goal of this solution is to merge k sorted arrays into a single sorted array.
6+
7+
## Possible Approaches
8+
9+
### 1. Sorting
10+
11+
- Create result array
12+
- Append all elements of all k lists to the array
13+
- Sort the array
14+
15+
#### Time Complexity
16+
17+
O((N*K)*log(N\*K)), K is number of arrays and N is average number of elements in the array
18+
19+
#### Space Complexity
20+
21+
O(N\*K)
22+
23+
Traversing all k lists, sorting the final list
24+
25+
### 2. Merge Sort
26+
27+
- Create a helper function that performs merge sort on two arrays using two pointers
28+
29+
- Call the function in pairs to effectively half the number of arrays every iteration.
30+
31+
- Return the output array
32+
33+
#### Time Complexity
34+
35+
O((N*K)*log(K))
36+
37+
Log(k) levels of recursion calls, and at each level, K arrays are traversed for merging.
38+
39+
#### Space Complexity
40+
41+
O((N*K)*log(K))
42+
43+
Log(k) levels and O(N\*K) space is required to store the answer every call.
44+
45+
### 3. Min Heap
46+
47+
- Most straightforward approach so far and the one implemented.
48+
- Iterate through all of the k arrays and append to a min heap implemented by a priority queue.
49+
- At each pass, append a single element from each array.
50+
- Pop the min element and insert the next element from which the element is extracted. If empty, array is merged.
51+
- Traverse the priority queue to store in a vector.
52+
- Return the vector
53+
54+
#### Time Complexity
55+
56+
O((N*K)*log(k))
57+
58+
Min-heap of size k used. For insertion and removal of elements, the time complexity is N \* Klog(K).
59+
60+
#### Space Complexity
61+
62+
O(N\*K)
63+
64+
Min-heap of size K used, for arrays averaging N elements.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include <bits/stdc++.h>
2+
vector<int> mergeKSortedArrays(vector<vector<int>>&kArrays, int k)
3+
{
4+
priority_queue<int, vector<int>, greater<int>> q;
5+
vector<int> result;
6+
for(int i=0; i<kArrays.size(); i++){
7+
for(int j=0; j<kArrays[i].size(); j++){
8+
q.push(kArrays[i][j]);
9+
}
10+
}
11+
while(!q.empty()){
12+
result.push_back(q.top());
13+
q.pop();
14+
}
15+
return result;
16+
}

0 commit comments

Comments
 (0)