String Coding Problems

Arrays Coding Problems

Sorting Coding Problems

Searching Coding Problems

Coding Algorithms

Tree Coding Problems

Stack Coding Problems

Linked list Coding Problems

Graph Coding Problems

Greedy Algorithms Coding Problems

Dynamic Programming Coding Problems

Matrix Coding Problems

Recursion Coding Problems

Number Theory Coding Problems

Backtracking Coding Problems

Heap Coding Problems

Brute Force Coding Problems

Implementation Coding Problems

Google Contests

Competitive Programming Coding


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.


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.


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




1 2 3
4 5 6
7 8 9

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:

  1. Firstly we created a min-heap of size k, and insert all the first element starting from index 0 of each array.
  2. Then we pop the root of the given min-heap and store it into our vector/array.
  3. 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.
  4. 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;
            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
    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();
        //push minimum element.
        //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.
    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;


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 

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.