Sort Matrix by Diagonals

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
1 7 3
9 8 2
4 5 6
Inputgrid = [[1,7,3],[9,8,2],[4,5,6]]
Output[[8,2,3],[9,6,7],[4,5,1]]
The bottom-left diagonals are sorted in non-increasing order, so [1, 8, 6] becomes [8, 6, 1], while the top-right diagonals are sorted in non-decreasing order, so [7, 2] becomes [2, 7].
Example 2
0 1
1 2
Inputgrid = [[0,1],[1,2]]
Output[[2,1],[1,0]]
The middle diagonal [0, 2] must be non-increasing, so it becomes [2, 0], and the other diagonals are already in the correct order.

Constraints

  • grid.length == grid[i].length == n
  • 1 <= n <= 10
  • -10^5 <= grid[i][j] <= 10^5

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate