Merge K Sorted Arrays Problem

Merge K Sorted Arrays Problem Statement

Given k arrays sorted in the same order – either non-increasing or non-decreasing – merge them all into one array sorted in the same order.

Example

{
"arr": [
[1, 3, 5, 7],
[2, 4, 6, 8],
[0, 9, 10, 11]
]
}

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Notes

Constraints:

  • 1 <= k <= 500
  • 2 <= size of an array <= 500
  • All k arrays are of the same size
  • -106 <= values in arrays <= 106

We have provided one solution for this problem.

Merge K Sorted Arrays Solution: Optimal

First step is to check the direction of sorting in the input data. Let us solve it for increasingly sorted input.

A naive approach would be to add all elements to one collection and then sort them out. We can build on our solution following the idea of the naive solution. At any given point of time, the smallest element would be from the pool of candidate smallest elements formed by adding the elements at start of all arrays. When we remove the smallest element from the pool, we will add the next element from that array.

We would use a min priority queue to carry out these operations. For input sorted in the decreasing order – a max priority queue.

Time Complexity

O(n * log(k)) where n is the total number of elements in all k arrays.

Auxiliary Space Used

O(k).

Space Complexity

O(k + n) where n is the total number of elements in all k arrays.

Code For Merge K Sorted Arrays Solution: Optimal


    /*
    * Asymptotic complexity in terms of total number of elements in all arrays `n`
    * and number of arrays `k`:
    * Time: O(n * log(k)).
    * Auxiliary space: O(k).
    * Total space: O(n + k).
    */
    static ArrayList<Integer> merge_arrays(ArrayList<ArrayList<Integer>> arr) {
        int k = arr.size();
        int N = arr.get(0).size();
        // Get appropriate priority queue
        PriorityQueue<Node> priorityQueue = getPriorityQueue(arr);
        for (int i = 0; i < k; i++) {
            priorityQueue.add(new Node(arr.get(i).get(0), i, 0));
        }
        ArrayList<Integer> ans = new ArrayList<Integer>();
        while (ans.size() < N * k) {
            Node rem = priorityQueue.poll();
            ans.add(rem.value);
            // Add the next element from the same row from which element is removed, if available
            if (rem.column + 1 < N) {
                priorityQueue.add(new Node(arr.get(rem.row).get(rem.column + 1), rem.row,
                    rem.column + 1));
            }
        }
        return ans;
    }

    static private PriorityQueue<Node> getPriorityQueue(ArrayList<ArrayList<Integer>> arr) {
        boolean isIncreasing = false, isDecreasing = false;
        // We will check if the input is sorted in increasing manner or
        // decreasing manner
        for (int i = 0; i < arr.size(); i++) {
            if (arr.get(i).get(0) < arr.get(i).get(arr.get(i).size() - 1)) {
                isIncreasing = true;
            }
            if (arr.get(i).get(0) > arr.get(i).get(arr.get(i).size() - 1)) {
                isDecreasing = true;
            }
        }

        if (isIncreasing) {
            // Make a min priority queue
            return new PriorityQueue<>();
        }
        if (isDecreasing) {
            // Make a max priority queue
            return new PriorityQueue<>(arr.size(), Collections.reverseOrder());
        }
        // Some error in test case; Code should never reach here;
        return null;
    }

    static class Node implements Comparable<Node> {
        int value;
        int row;
        int column;

        Node(int xx, int yy, int zz) {
            value = xx;
            row = yy;
            column = zz;
        }

        @Override
        public int compareTo(Node o) {
            return Long.compare(this.value, o.value);
        }
    }

We hope that these solutions to merge k sorted arrays problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Binary Tree Level Order Traversal Problem with Examples

Jump Game

Zigzag Sort Problem

Boggle Solver Problem

Shortest String Transformation Using A Dictionary Problem

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC