Median of two sorted arrays
You are given two sorted arrays 'A' & 'B' of sizes 'N' & 'M'. You need to find the median of the two arrays when merged. If the total number of elements i.e., N + M is even then the median will be the mean of two medians.
Example:
Let array A = { 2, 4, 6, 8 } and array B = { 1, 3, 5, 7 }.
The array after merging A and B will be { 1, 2, 3, 4, 5, 6, 7, 8 }.
Here two medians are 4 & 5. So the median will be a mean of 4 & 5, which is 4.5.
Follow Up
Can you solve this in O(min(log N, log M)) time complexity?
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers ‘N’ and ‘M’ representing the sizes of the two arrays.
The second line of each test case contains 'N' space-separated integers representing the elements of the first array.
The third line of each test case contains 'M' space-separated integers representing the elements of the second array.
Output format :
For each test case, print a single line containing a single integer denoting the median of the combined array.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10 ^ 6
1 <= M <= 10 ^ 6
1 <= A[i] <= 10 ^ 9
1 <= B[i] <= 10 ^ 9
Time limit: 1 sec.
CodingNinjas
author
2y
Sorting
The first approach is by joining the array and again sorting is to get median.
The algorithm is as follows:
- Create a new array of size of total number of elements.
- Insert elements of both the arr...read more
CodingNinjas
author
2y
Two pointer
The second approach is using a two-pointer approach to get middle elements.
The algorithm is as follows:
- Initialize two pointers i and j to 0.
- Move a pointer forward which has a smaller value...read more
CodingNinjas
author
2y
Binary Search
The third approach is using binary search to find median.
The algorithm is as follows:
- Use Binary Search to partition the smaller array in two parts.
- Find the partition of the second array ...read more
Add answer anonymously...
Top Nagarro Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Top HR questions asked in Nagarro Software Developer Intern
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