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
Sort Matrix by Diagonals In-Place Diagonal Sorting Approach INPUT MATRIX 3 3 1 2 2 1 4 2 2 Diagonal Classification: Bottom-Left (desc) Main Diagonal (desc) Top-Right (asc) Input: grid = [[3,3,1], [2,2,1],[4,2,2]] ALGORITHM STEPS 1 Identify Diagonals Split into bottom-left and top-right triangles 2 Extract Diagonal Collect elements along each diagonal line 3 Sort In-Place Bottom-left: descending Top-right: ascending 4 Place Back Write sorted values back to matrix Example: Main Diagonal Before: 3 2 2 After: 3 2 2 (desc) FINAL RESULT 3 1 1 3 2 1 4 2 2 Color Legend: Main Diagonal Bottom-Left (desc) Top-Right (asc) Output: [[3,1,1], [3,2,1],[4,2,2]] OK Key Insight: Each diagonal can be identified by (row - col). Bottom-left diagonals have (row - col) >= 0, while top-right diagonals have (row - col) < 0. Sort each diagonal independently in-place without extra space by using two-pointer or bubble sort technique along the diagonal. TutorialsPoint - Sort Matrix by Diagonals | In-Place Diagonal Sorting Approach
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