Problem
You are given an n x n
square matrix of integers grid
. Return the matrix such that:
- The diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order.
- The diagonals in the top-right triangle are sorted in non-decreasing order.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
grid.length == grid[i].length == n
1 <= n <= 10
-10^5 <= grid[i][j] <= 10^5
Examples
Solution
Method 1 - Diagonal Identification and Sorting
Intuition: We need to identify diagonals and sort them based on their position. Diagonals can be identified by the difference i - j
. For diagonals where i - j >= 0
(bottom-left triangle including main diagonal), sort in non-increasing order. For diagonals where i - j < 0
(top-right triangle), sort in non-decreasing order.
Approach:
- Group matrix elements by their diagonal index (
i - j
) - For each diagonal, extract all elements
- Sort elements based on diagonal position:
i - j >= 0
: sort in descending order (non-increasing)i - j < 0
: sort in ascending order (non-decreasing)
- Place sorted elements back into the matrix
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n² log n)
where n is the matrix dimension (sorting each diagonal) - 🧺 Space complexity:
O(n²)
for storing diagonal elements and result matrix