Home » Interview coding problems/challenges

# Merge K Sorted Arrays

**Merge K Sorted Arrays**: Given K sorted arrays arranged in form of a matrix of size K*N, you are required to merge them into single sorted array.

Submitted by Divyansh Jaipuriyar, on August 22, 2020

**Problem statement:**

Given *K* sorted arrays arranged in form of a matrix of size *K*N*, you are required to merge them into single sorted array.

**Problem description:**

The problem basically asks you to find the sorted array of entire matrix using the property that the arrays are already sorted and keeping in mind about the time constraints.

**Input:**

The first line of input is the *T* number of test cases, each test case consist of *K* and *N* the number of arrays and size of each array.

**Output:**

Print the sorted form of merged arrays for each test case in separate line.

**Constrains:**

1<=T<=50 1<=K,N<=1000

**Examples:**

Input: T=1 K=3,N=3 1 2 3 4 5 6 7 8 9 Output: 1 2 3 4 5 6 7 8 9 as this is the possible sorted array after merging them into single unit.

**Solution approach:**

The basic naive method to approach this method to create an array of size (*k*N*) and store all the elements of the given matrix and then sort the entire array of given size and print that array. But the time complexity for that method would be huge as *O(K*N*log(K*N))*, and there is no use of the condition that the array is already sorted.

The optimized method to solve the given problem is with the help of min-heap.

Following steps are used in the heap method:

- Firstly we created a min-heap of size k, and insert all the first element starting from index 0 of each array.
- Then we pop the root of the given min-heap and store it into our vector/array.
- Then we check whether there is any element left in the array from where this popped element belongs, if it is not empty then we push the next element from that array itself.
- We repeat the above steps until the heap is empty.

**Time complexity** for this approach in the worst case is: **O(K*N*log(K))**

**Space complexity** for this approach in the worst case is: **O(K*N)**

**C++ Implementation:**

#include <bits/stdc++.h> using namespace std; typedef long long ll; //structure for creating //three values in single unit. struct triplet { //val is the value of element. //r is the row number in given matrix. //c is the col number in given matrix. ll val, r, c; }; //comparison function used to create //min heap with triplet value element. struct comparison { bool operator()(const triplet& t1, const triplet& t2) { if (t1.val > t2.val) return true; else return false; } }; //solve function wihch print //given values in sorted manner. void solve(vector<vector<ll> >& v1, ll K, ll N) { //priority_queue(min heap) with //triplet as its element. priority_queue<triplet, vector<triplet>, comparison> pq; //iterate through all arrays //and store first element of each //arrays. for (ll i = 0; i < K; i++) { //v1[i][0] is the value of element. //i is the row number. //0 is the colmn number. pq.push({ v1[i][0], i, 0 }); } //vector to store sorted values. vector<ll> v2; //iterate till heap is not empty. while (!pq.empty()) { triplet temp = pq.top(); pq.pop(); //push minimum element. v2.push_back(temp.val); //check if there is any //element remaining in same row //or it is tha last element of that row. if (temp.c + 1 < N) { //move right to current element. temp.c += 1; temp.val = v1[temp.r][temp.c]; //push next element into heap. pq.push(temp); } } for (ll i = 0; i < v2.size(); i++) cout << v2[i] << " "; cout << "\n"; } int main() { cout << "Enter number of test cases: "; ll t; cin >> t; while (t--) { cout << "Enter K and N: "; ll K, N; cin >> K >> N; //matrix for input of K //arrays with size N each. vector<vector<ll> > v1(K, vector<ll>(N, 0)); for (ll i = 0; i < K; i++) for (ll j = 0; j < N; j++) cin >> v1[i][j]; //call solve function. solve(v1, K, N); } return 0; }

**Output:**

Enter number of test cases: 3 Enter K and N: 3 3 1 2 3 5 9 10 2 5 8 1 2 2 3 5 5 8 9 10 Enter K and N: 4 4 4 5 6 7 11 12 13 14 0 1 2 3 6 7 8 9 0 1 2 3 4 5 6 6 7 7 8 9 11 12 13 14 Enter K and N: 2 2 1 2 3 4 1 2 3 4

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.