"Sort Matrix by Diagonals" is a matrix manipulation problem where you are asked to sort the elements within each diagonal of an matrix. The sorting rules usually differ based on the diagonal's location:
This problem requires you to correctly identify all diagonals in a 2D grid and apply the correct sorting logic to each group of elements.
Companies like Microsoft and Amazon ask this question to test a candidate's ability to navigate 2D arrays. It evaluates your understanding of grid indices—specifically, how to group elements that belong to the same diagonal (where the difference row - col is constant). It also tests your ability to apply conditional logic and manage multiple sub-tasks (extracting, sorting, and re-inserting) within a single problem.
The primary pattern is Diagonal Traversal and Sorting.
row - col.row - col) and the value is a list of elements on that diagonal.Input: [[1, 7], [2, 8]]
One common mistake is incorrectly identifying the diagonals, especially for non-square matrices (though this problem often uses ). Another mistake is applying the wrong sorting order to the wrong triangle. Candidates also sometimes struggle with the "in-place" requirement, accidentally creating many unnecessary copies of the matrix data, which can lead to excessive memory usage.
When you see a matrix diagonal problem, remember the rule: row - col is constant for top-left to bottom-right diagonals, and row + col is constant for top-right to bottom-left diagonals. Mastering this index-based grouping will make any sort matrix by diagonals coding problem much easier to solve. Practice extracting these diagonals into lists and re-filling them to build your confidence with 2D array navigation.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sort the Students by Their Kth Score | Medium | Solve | |
| Sort the Matrix Diagonally | Medium | Solve | |
| Minimum Operations to Make a Uni-Value Grid | Medium | Solve | |
| Largest Submatrix With Rearrangements | Medium | Solve | |
| Best Meeting Point | Hard | Solve |