The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain two integers ‘N’ and ‘M’ denoting the number of rows and columns, respectively.
Next ‘N’ lines contain ‘M’ space-separated integers each denoting the elements in the matrix.
For each test case, print an integer which is the overall median of the given matrix.
Output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of. Just implement the given function.
1 <= 'T' <= 50
1 <= 'N' , 'M' <= 100
1 <= 'MATRIX'['I']['J'] <= 10 ^ 5
'N' * 'M' is always an odd number.
Where 'MATRIX'['I']['J'] denotes the value at ('I', 'J')th cell in the matrix.
Time limit: 1 sec
Since, the median is the middle number in a sorted, ascending or descending, list of numbers, our basic idea is to generate the list of integers from the given matrix in a sorted manner. The steps are as follows:
The basic idea of this approach is to utilize the fact that elements in the row are stored in a sorted manner.
Suppose we want to create a sorted (in non-decreasing order) list of integers from the given matrix. Now let’s try to append the integers in the list one by one. Consider the first element of each row; the minimum of those elements will be the minimum element of the matrix itself. Why? Because the first element of each row is the minimum element of that row.
Now, to find the second smallest element, we will remove the smallest element, and we will consider the next element (2nd element) of the row where the minimum element was found. Following the steps mentioned above, we can easily find the sorted list of integers.
The above image explains the first five steps of the algorithm. The highlighted element is the minimum element of the matrix in each step. We can observe that we just need to consider elements of the first column to find the minimum. Therefore, we can use a min-heap data structure to operate efficiently.
Since the median is always the middle element in the sorted list, we simply do the above operation for ('N' * 'M')/2 times. And then the next smallest element will be the median.
The steps are as follows:
The core idea of this approach is to utilize the property of the median and the sorted rows. Note that for a given list of integers whose length is 'N' * 'M', the median is the smallest number that is greater than or equal to at least ('N' * 'M')/2 elements in the list.
Let ‘X’ be the potential median of the matrix. Now, 'X’ can be any number from the matrix. We can do a binary search to find the ‘X’.
Search In A Sorted 2D Matrix
Spiral Matrix
Spiral Matrix
Spiral Matrix
Sort 0s, 1s, 2s
Day 28 : Fake Coin Problem
Day 28 : Fake Coin Problem
Search In A Rotated Sorted Array II