If M = 4 and N = 5, and the matrix is:
{ {1, 2, 3, 4, 5},
{2, 3, 4, 5, 6},
{2, 3, 5, 6, 7},
{1, 3, 4, 5, 6} }
For the given matrix, 3 is the possible smallest element that is present in all the rows.
The first line contains a single integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each testcase contains two integers ‘M’ and ‘N’, denoting the number of rows and columns respectively.
The next ‘M’ line contains ‘N’ integers, denoting the elements of the matrix.
For example:

The matrix above contains 3 rows and 4 columns ans will be represented as:
4 3
1 2 3 4
4 6 7 8
9 10 11 12
For each test case print a single integer denoting the smallest common element.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= M,N <= 100
0 <= matrix[i][j] <= 10^9
Time limit: 1 sec
2
2 3
1 2 3
2 3 6
1 5
1 2 3 4 5
2
1
For test case 1 :
The given grid is:

2 is the smallest element present in both 1st and 2nd row.
For test case 2 :
The given grid is:

As there is only a single row, so the smallest element in that row will be the smallest common element.
2
2 2
10 20
30 40
1 1
5
-1
5
Iterate elements of the first-row one by one, and for each element check if it is present in each row.
The steps are as follows:
Iterate elements of the first-row one by one, and for each element check if it is present in each row using binary search.
The steps are as follows:
Create a hash map with elements of the first row, set the value of each key to 1 in the hash map. Now iterate the remaining elements of M-1 rows, if the element is present in the hash map then increment the value corresponding to it, but remember not to double count, to take care of this ignore the element if it’s equal to the previous element of that row.
Finally, the hash map will store the count of row-wise occurrences. To get the smallest answer, iterate through the elements of the first row, and check the value corresponding to it in the hash map if the value is equal to the number of rows.
Note: We could have created a hash map of all the elements of the matrix, but that would have a very high space complexity. And we tackled it by just considering the elements of the first row in our hash map, as we are if an answer exists it must be an element of the first row also.
The steps are as follows: