AlgoLounge

Sort Matrix by Diagonals

medium

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.

Examples

Example 1

Input:  grid = [[1,7,3],[9,8,2],[4,5,6]]
Output: [[8,2,3],[9,6,7],[4,5,1]]

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]]

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]]

Diagonals with exactly one element are already in order, so no changes are needed.

Constraints

  • grid.length == grid[i].length == n
  • 1 <= n <= 10
  • -10⁵ <= grid[i][j] <= 10⁵
TypeScript
Loading editor…
List of test cases (10)
Case 1
grid = [[1,7,3],[9,8,2],[4,5,6]]
Case 2
grid = [[0,1],[1,2]]
Case 3
grid = [[1]]
Case 4
grid = [[-1,-9,3],[4,-5,2],[7,8,0]]
Case 5
grid = [[4,3,2,1],[8,7,6,5],[12,11,10,9],[16,15,14,13]]
Case 6
grid = [[9,1,2],[8,7,3],[6,5,4]]
Case 7
grid = [[5,5,5],[5,5,5],[5,5,5]]
Case 8
grid = [[100000,-100000],[-99999,99999]]
Case 9
grid = [[3,8,4,1,9],[7,2,6,5,0],[4,9,1,8,3],[6,0,7,2,5],[1,3,9,4,8]]
Case 10
grid = [[2,-1,4,0],[3,2,-2,5],[1,7,2,-3],[6,8,9,2]]