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],[3,2,1],[4,2,2]]
💡 Note: Bottom-left diagonals [4], [2,2], [3,2,2] sorted descending. Top-right diagonals [3,1], [1] sorted ascending. Main diagonal [3,2,2] stays [3,2,2] when sorted descending.
Example 2 — Larger Matrix
$ Input: grid = [[7,6,5],[4,3,2],[1,8,9]]
Output: [[7,5,6],[4,3,2],[1,8,9]]
💡 Note: Bottom-left: [1], [4,8], [7,3,9] sorted descending. Top-right: [6,2], [5] sorted ascending. Result has properly sorted diagonals.
Example 3 — Already Sorted
$ Input: grid = [[5,4],[3,2]]
Output: [[5,2],[4,3]]
💡 Note: Bottom-left diagonal [5,2] sorted descending stays [5,2]. 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
Sort Matrix by DiagonalsInput Matrix331221422Bottom-left triangle: Sort ↓ (descending)Top-right triangle: Sort ↑ (ascending)Diagonals identified by (row - col):d=2: [4] → [4]d=1: [2,2] → [2,2]d=0: [3,2,2] → [3,2,2]d=-1: [3,1] → [1,3]d=-2: [1] → [1]Output Matrix311321422Each diagonal sorted according to its triangle position
Understanding the Visualization
1
Input Matrix
3×3 matrix with unsorted diagonals
2
Identify Triangles
Bottom-left (blue) sorted descending, top-right (yellow) sorted ascending
3
Sorted Result
Each diagonal properly sorted according to rules
Key Takeaway
🎯 Key Insight: Use (row - col) to identify diagonals, then sort based on triangle position
Asked in
Google 25 Facebook 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen