Median of Two Sorted Arrays
Given two sorted arrays A
and B
of sizes N
and M
, find the median of the merged array formed by combining arrays A
and B
. If the total number of elements, N + M
, is even, the median will be the mean of the two middle elements.
Input:
The first line of input contains an integer 'T' representing the number of test cases.
Each test case contains:
- Two space-separated integers 'N' and 'M' denoting the sizes of arrays 'A' and 'B'.
- A line with 'N' space-separated integers representing the elements of array 'A'.
- A line with 'M' space-separated integers representing the elements of array 'B'.
Output:
For each test case, output a single line with a number representing the median of the combined array. Each test case output should be on a new line.
Example:
Input:
A = {2, 4, 6, 8} and B = {1, 3, 5, 7}.
The merged array is {1, 2, 3, 4, 5, 6, 7, 8}.
Since the total number of elements is even, the medians are 4 and 5.
Thus, the median is the mean of 4 and 5, which is 4.5.
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.
Note:
You do not need to print anything manually; just implement the function to return the result.
AnswerBot
5d
Find the median of two sorted arrays by merging them and calculating the median of the combined array.
Merge the two sorted arrays into one sorted array.
Calculate the median of the merged array based o...read more
Help your peers!
Add answer anonymously...
Top AlphaSense Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in AlphaSense Software Developer
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