"Sort the Matrix Diagonally" is a variation of matrix sorting where every diagonal in a 2D matrix (from top-left to bottom-right) must be sorted in ascending order. Unlike some variations, this one typically applies the same sorting rule to every single diagonal in the matrix.
The challenge is to efficiently access all diagonals, sort the elements within them, and then re-populate the matrix. For an matrix, there are such diagonals.
Companies like Amazon and Walmart Labs ask this to verify that a candidate can work with multidimensional data structures. It tests your ability to identify the relationship between indices in a grid. Specifically, it checks if you know that elements and are on the same diagonal if and only if . It also evaluates your ability to manage collections of data within a matrix.
The primary pattern is Hash Map-based Diagonal Sorting.
row - col. Append each matrix[row][col] to the list corresponding to its key.row - col and place it in the cell.Input: [[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]]
One common mistake is incorrectly identifying the diagonal keys. Another mistake is not being efficient—some candidates try to find each diagonal one by one starting from the edges, which is much more complex than the simple row - col hash map approach. Finally, forgetting to clear or properly manage the lists of elements as they are popped can lead to reused values or index errors.
Mastering the "Sort the Matrix Diagonally interview question" is all about that one key insight: row - col is the unique ID for a diagonal. Once you have that, the problem becomes a simple application of sorting lists. Practice this grouping technique, as it appears in many other matrix problems like "Toeplitz Matrix" or finding the longest diagonal with a certain property.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sort the Students by Their Kth Score | Medium | Solve | |
| Sort Matrix by Diagonals | Medium | Solve | |
| Largest Submatrix With Rearrangements | Medium | Solve | |
| Minimum Operations to Make a Uni-Value Grid | Medium | Solve | |
| Best Meeting Point | Hard | Solve |