Problem
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix’s end. For example, the matrix diagonal starting from mat[2][0]
, where mat
is a 6 x 3
matrix, includes cells mat[2][0]
, mat[3][1]
, and mat[4][2]
.
Given an m x n
matrix mat
of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Examples
Example 1:
$$ Input: \begin{array}{cccc} \colorbox{yellow}3 & \colorbox{lightgray}3 & \colorbox{cyan}1 & \colorbox{orange}1 \\ \colorbox{lightgreen}2 & \colorbox{yellow}2 & \colorbox{lightgray}1 & \colorbox{cyan}2 \\ \colorbox{lightblue}1 & \colorbox{lightgreen}1 & \colorbox{yellow}1 & \colorbox{lightgray}2 \\ \end{array} \\ , Output: \begin{array}{cccc} \colorbox{yellow}1 & \colorbox{lightgray}1 & \colorbox{cyan}1 & \colorbox{orange}1 \\ \colorbox{lightgreen}1 & \colorbox{yellow}2 & \colorbox{lightgray}2 & \colorbox{cyan}2 \\ \colorbox{lightblue}1 & \colorbox{lightgreen}2 & \colorbox{yellow}3 & \colorbox{lightgray}3 \\ \end{array} $$
|
|
Example 2:
|
|
Solution
Method 1 - Iteration
To solve this problem, you need to sort each diagonal of the matrix individually. A diagonal in the matrix starts from the topmost row or the leftmost column and extends diagonally to the bottom-right until the matrix’s end.
Approach
- Traverse each diagonal starting from the top row.
- Traverse each diagonal starting from the left column (excluding the top-left corner since it’s already covered in the first step).
- Extract each diagonal into a list, sort it, and place it back into the matrix.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O((m + n) * d log(d))
. Sorting each diagonal will takeO(d log d)
, whered
is the length of the diagonal. Since there are aboutm + n - 1
diagonals, the overall complexity isO((m + n) * min(m, n) log(min(m, n)))
. - 🧺 Space complexity:
O(d)
, where the space is used for storing each diagonal’s elements.