Sort Matrix by Diagonals Problem
Description
LeetCode Problem 3446.
You are given an n x n square matrix of integers grid. Return the matrix such that:
- The diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order.
- The diagonals in the top-right triangle are sorted in non-decreasing order.
Example 1:
Input: grid = [[1,7,3],[9,8,2],[4,5,6]]
Output: [[8,2,3],[9,6,7],[4,5,1]]
Explanation:

The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:
- [1, 8, 6] becomes [8, 6, 1].
- [9, 5] and [4] remain unchanged.
The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:
- [7, 2] becomes [2, 7].
- [3] remains unchanged.
Example 2:
Input: grid = [[0,1],[1,2]]
Output: [[2,1],[1,0]]
Explanation:

The diagonals with a black arrow must be non-increasing, so [0, 2] is changed to [2, 0]. The other diagonals are already in the correct order.
Example 3:
Input: grid = [[1]]
Output: [[1]]
Explanation:
Diagonals with exactly one element are already in order, so no changes are needed.
Constraints:
grid.length == grid[i].length == n1 <= n <= 10-10^5 <= grid[i][j] <= 10^5
Solution
Approach: Sort Each Diagonal
The matrix is at most 10 x 10, so we can simply handle every diagonal on its own.
Start from each cell of the first column (rows n-2 down to 0, plus the main diagonal) and walk down and to the right, collecting the values. These diagonals belong to the bottom-left triangle, so sort them and write them back from largest to smallest. Then start from each cell of the last column (rows n-2 down to 1) and walk up and to the left. These diagonals belong to the top-right triangle; sorting the values and writing the largest one at the bottom-right end leaves each diagonal non-decreasing from top-left to bottom-right. Diagonals of length one never change.
Complexity: O(n2 log n) time and O(n) extra space.
class Solution:
def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
for k in range(n - 2, -1, -1):
i, j = k, 0
t = []
while i < n and j < n:
t.append(grid[i][j])
i += 1
j += 1
t.sort()
i, j = k, 0
while i < n and j < n:
grid[i][j] = t.pop()
i += 1
j += 1
for k in range(n - 2, 0, -1):
i, j = k, n - 1
t = []
while i >= 0 and j >= 0:
t.append(grid[i][j])
i -= 1
j -= 1
t.sort()
i, j = k, n - 1
while i >= 0 and j >= 0:
grid[i][j] = t.pop()
i -= 1
j -= 1
return grid