Sort the Matrix Diagonally - Problem
Sort the Matrix Diagonally is a fascinating matrix manipulation problem that challenges you to think about diagonal patterns in 2D arrays.

Imagine a matrix where you need to sort each diagonal line that runs from top-left to bottom-right. A matrix diagonal is defined as a line of cells starting from either:
• Any cell in the topmost row (first row)
• Any cell in the leftmost column (first column)

Each diagonal continues in the bottom-right direction until it reaches the matrix boundary.

Example: In a 6×3 matrix, the diagonal starting from mat[2][0] includes cells mat[2][0] → mat[3][1] → mat[4][2].

Your task: Given an m × n matrix of integers, sort each diagonal in ascending order and return the transformed matrix.

🎯 Goal: Transform the matrix so that every diagonal from top-left to bottom-right is sorted in ascending order.

Input & Output

basic_3x3_matrix.py — Python
$ Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
💡 Note: Each diagonal is sorted: main diagonal [3,2,1] becomes [1,2,3], diagonal starting from [0,1] is [3,2,1] becomes [1,2,3], and so on.
single_element.py — Python
$ Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
💡 Note: A larger matrix where each diagonal from top-left to bottom-right is sorted independently while maintaining the original matrix structure.
edge_case_single.py — Python
$ Input: mat = [[1,2],[3,4]]
Output: [[1,2],[3,4]]
💡 Note: In a 2x2 matrix, each diagonal has only one element, so no sorting is needed and the matrix remains unchanged.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 100
  • 1 ≤ mat[i][j] ≤ 100

Visualization

Tap to expand
Matrix Diagonal Sorting VisualizationBefore831794265Sort DiagonalsAfter831724965Diagonal Grouping Process8Diagonal -2: [8]37Diagonal -1: [3,7] → [3,7]192Diagonal 0: [1,9,2] → [1,2,9]46Diagonal 1: [4,6] → [4,6]
Understanding the Visualization
1
Identify Diagonal Patterns
Recognize that cells sharing the same (row - col) value belong to the same diagonal
2
Group Elements
Collect all elements from each diagonal using the mathematical invariant
3
Sort Each Group
Sort elements within each diagonal group in ascending order
4
Redistribute
Place sorted elements back to their respective diagonal positions
Key Takeaway
🎯 Key Insight: The mathematical property (i-j = constant) for diagonal elements allows us to efficiently group, sort, and redistribute elements while preserving the matrix structure.
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 15
52.4K Views
Medium Frequency
~15 min Avg. Time
2.2K 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