Sort Matrix by Diagonals - Problem
You are given an n × n square matrix of integers grid. Your task is to return the matrix such that:
• The diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order (descending)
• The diagonals in the top-right triangle are sorted in non-decreasing order (ascending)
Each diagonal is a line of cells where the difference between row and column indices remains constant.
Input & Output
Example 1 — Basic 3×3 Matrix
$
Input:
grid = [[3,3,1],[2,2,1],[4,2,2]]
›
Output:
[[3,1,1],[2,2,3],[4,2,2]]
💡 Note:
Bottom-left diagonals [4], [2,2] sorted descending stay the same. Main diagonal [3,2,2] sorted descending stays [3,2,2]. Top-right diagonals [3,1], [1] sorted ascending become [1,3], [1].
Example 2 — Larger Matrix
$
Input:
grid = [[7,6,5],[4,3,2],[1,8,9]]
›
Output:
[[8,2,5],[7,3,6],[4,1,9]]
💡 Note:
Bottom-left: [1], [4,8], [7,3,9] sorted descending become [1], [8,4], [9,7,3]. Top-right: [6,2], [5] sorted ascending become [2,6], [5]. Result has properly sorted diagonals.
Example 3 — Already Sorted
$
Input:
grid = [[5,4],[3,2]]
›
Output:
[[5,3],[4,2]]
💡 Note:
Bottom-left diagonal [5,2] sorted descending stays [5,2]. Main diagonal contains only [5] at (0,0) and [2] at (1,1), giving [5,2] descending. Top-right diagonal [4] stays [4]. Cross-diagonal [3] stays [3].
Constraints
- n == grid.length == grid[i].length
- 1 ≤ n ≤ 100
- 1 ≤ grid[i][j] ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code