![]() |
VOOZH | about |
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of the matrix in sorted order.
Example:
Input: mat[][] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
Output: 10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
We can use Young Tableau to solve the above problem. The idea is to consider the given 2D array as Young Tableau and call extract minimum O(N)
Algorithm:
Below is the implementation of this approach:
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
Time complexity of extract minimum is O(N) and it is called O(N2) times. Therefore the overall time complexity is O(N3).
Auxiliary Space: O(N2)
Another approach: The idea is to keep all elements of the matrix in a one-dimensional array and then sort the array and print all values in it.
Below is the implementation of the above approach:
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
Time Complexity: O(N2log(N2))
Auxiliary Space: O(N2)
A better solution is to use the approach used for merging k sorted arrays. The idea is to use a Min Heap of size N which stores elements of first column. They do extract minimum. In extract minimum, replace the minimum element with the next element of the row from which the element is extracted.
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
Time complexity: O(N2LogN).
Auxiliary Space: O(N)
Exercise:
Above solutions work for a square matrix. Extend the above solutions to work for an M*N rectangular matrix.