Merge K sorted arrays
You have been given ‘K’ different arrays/lists, which are sorted individually (in ascending order). You need to merge all the given arrays/list such that the output array/list should be sorted in ascending order.
Input Format :
The first line of input contains an integer T, the number of test cases.
The first line of each test case contains an integer that denotes the value of K.
The next 2*K lines of each test case follow:
The first line contains an integer ‘N’ denoting the size of the array.
The second line contains N space-separated integers.
Output Format :
The first and only line of output contains space-separated elements of the merged and sorted array, as described in the task.
Note :
You don’t have to print anything; it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 5
1 <= K <= 5
1 <= N <= 20
-10^5 <= DATA <= 10^5
Time Limit: 1 sec
CodingNinjas
author
2y
Approach 1 (Brute Force) :
Create an output array and and one by one copy all arrays to it. Finally, sort the output array using. This approach takes O(N Logn N) time where N is count of all elements.
...read more
CodingNinjas
author
2y
Sorting
- Create an output array ‘RESULT’.
- Traverse all the given arrays from start to end and insert all the elements in the output array ‘RESULT’.
- Sort the ‘RESULT’ and return it.
CodingNinjas
author
2y
Divide and Conquer
The idea is based on the divide and conquer strategy. We take pairs of arrays at each step. Then merge the pairs using the two-pointer technique of merging two sorted arrays. Thus, a...read more
CodingNinjas
author
2y
Heaps
The idea is to use the concept of min-heap. As we know, the root of the min-heap is always the minimum element in the heap. Thus, insert the first elements of all the ‘K’ arrays into the heap alo...read more
Add answer anonymously...
Top Publicis Sapient Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Publicis Sapient Software Developer
>
Publicis Sapient Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app