Register for our webinar

1 hour

Step 1

Step 2

Congratulations!

You have registered for our webinar

Oops! Something went wrong while submitting the form.

Step 1

Step 2

Confirmed

You are scheduled with Interview Kickstart.

Redirecting...

Oops! Something went wrong while submitting the form.

Head of Career Skills Development & Coaching

*Based on past data of successful IK students

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.

```
{
"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]
```

Constraints:

- 1 <=
`k`

<= 500 - 2 <= size of an array <= 500
- All
`k`

arrays are of the same size - -10
^{6}<= values in arrays <= 10^{6}

We have provided one solution for this problem.

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.

O(n * log(k)) where `n`

is the total number of elements in all `k`

arrays.

O(k).

O(k + n) where `n`

is the total number of elements in all `k`

arrays.

```
/*
* 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:

- Back-end Engineering Interview Course
- Front-end Engineering Interview Course
- Full Stack Developer Interview Course

To learn more, register for the FREE webinar.

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

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.

```
{
"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]
```

Constraints:

- 1 <=
`k`

<= 500 - 2 <= size of an array <= 500
- All
`k`

arrays are of the same size - -10
^{6}<= values in arrays <= 10^{6}

We have provided one solution for this problem.

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.

O(n * log(k)) where `n`

is the total number of elements in all `k`

arrays.

O(k).

O(k + n) where `n`

is the total number of elements in all `k`

arrays.

```
/*
* 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:

- Back-end Engineering Interview Course
- Front-end Engineering Interview Course
- Full Stack Developer Interview Course

To learn more, register for the FREE webinar.

**Attend our free webinar to amp up your career and get the salary you deserve.**

Hosted By

Ryan Valles

Founder, Interview Kickstart

- Designed by 500 FAANG+ experts
- Live training and mock interviews
- 17000+ tech professionals trained

00

Days

:

00

Hrs

:

00

Mins

:

00

Secs