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
4mo
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...
AlphaSense Software Developer interview questions & answers
A Software Developer was asked 11mo agoQ. Write a program to print the last 10 lines of a file, and configure it to run ev...read more
A Software Developer was asked 11mo agoQ. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q. What is a peer-to-peer connection?
Popular interview questions of Software Developer
A Software Developer was asked 11mo agoQ1. Write a program to print the last 10 lines of a file, and configure it to run ev...read more
A Software Developer was asked 11mo agoQ2. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q3. What is a peer-to-peer connection?
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

