Problem Description
Given an n x n square matrix, sort each of its diagonals in one of two ways:
- For diagonals in the bottom-left triangle (including the main diagonal), sort them in non-increasing order.
- For diagonals in the top-right triangle, sort them in non-decreasing order. Then, update the matrix with the sorted diagonals.
Key Insights
- Diagonals in a matrix can be grouped by the value of (row index - column index).
- If the key (i - j) is non-negative (>= 0), the diagonal belongs to the bottom-left triangle; if it is negative (< 0), the diagonal is in the top-right triangle.
- Collect each diagonal into a list, sort the list based on the required order, and then reassign the sorted elements back to their respective positions.
- Process each diagonal independently to keep the solution clear and modular.
Space and Time Complexity
Time Complexity: O(n^2 log n) – Each diagonal (at most n elements) is sorted. Space Complexity: O(n^2) – Extra space is used to store the diagonals in a dictionary.
Solution
The solution involves iterating over each cell in the matrix and grouping elements into diagonals using the key (i - j). For each diagonal:
- If the key is >= 0 (bottom-left), sort the list in descending order.
- If the key is < 0 (top-right), sort the list in ascending order. Once sorted, iterate over the matrix again and, based on the same diagonal key, replace the element with the next value from the sorted list. The dictionary of diagonals is used to both gather and then reassign the elements with the sorted order.