 Register for our webinar

### How to Nail your next Technical Interview

1 hour 1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name  Step 1  Step 2
Congratulations!
You have registered for our webinar Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone  Step 1  Step 2 Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.  ## You may be missing out on a 66.5% salary hike* ### Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students Help us know you better!

## How many years of coding experience do you have?

Oops! Something went wrong while submitting the form.  ## FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Oops! Something went wrong while submitting the form.  # 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.

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++) {
}
ArrayList<Integer> ans = new ArrayList<Integer>();
while (ans.size() < N * k) {
Node rem = priorityQueue.poll();
// Add the next element from the same row from which element is removed, if available
if (rem.column + 1 < N) {
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:

### Try yourself in the Editor

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

# 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.

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++) {
}
ArrayList<Integer> ans = new ArrayList<Integer>();
while (ans.size() < N * k) {
Node rem = priorityQueue.poll();
// Add the next element from the same row from which element is removed, if available
if (rem.column + 1 < N) {
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:

## Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve. Hosted By
Ryan Valles
Founder, Interview Kickstart Accelerate your Interview prep with Tier-1 tech instructors 360° courses that have helped 14,000+ tech professionals 100% money-back guarantee*