Sort Matrix by Diagonals - Problem
You are given an n ร n square matrix of integers. Your task is to sort specific diagonals in different orders to create a beautifully organized pattern:
- Bottom-left triangle diagonals (including the main diagonal): Sort in non-increasing order (largest to smallest)
- Top-right triangle diagonals: Sort in non-decreasing order (smallest to largest)
Think of it as creating a mountain peak along the main diagonal - values decrease as you go down-left, and increase as you go up-right!
Example: In a 3ร3 matrix, diagonal [1,5,9] becomes [9,5,1] (decreasing), while diagonal [3,7] becomes [3,7] (increasing).
Input & Output
example_1.py โ Basic 3x3 Matrix
$
Input:
grid = [[3,1,2],[5,7,4],[8,6,9]]
โบ
Output:
[[9,1,2],[6,7,4],[5,5,3]]
๐ก Note:
Main diagonal [3,7,9] becomes [9,7,3] (decreasing). Diagonal [5,6] becomes [6,5] (decreasing). Top-right diagonals [1], [2,4] remain [1], [2,4] (increasing).
example_2.py โ 4x4 Matrix
$
Input:
grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
โบ
Output:
[[16,2,3,4],[14,11,7,8],[10,15,6,12],[13,9,5,1]]
๐ก Note:
Bottom-left diagonals sorted in decreasing order: [1,6,11,16]โ[16,11,6,1], [5,10,15]โ[15,10,5], etc. Top-right diagonals sorted in increasing order.
example_3.py โ Single Element
$
Input:
grid = [[42]]
โบ
Output:
[[42]]
๐ก Note:
Single element matrix remains unchanged as there's only the main diagonal with one element.
Constraints
- 1 โค n โค 1000
- 1 โค grid[i][j] โค 105
- The matrix is always square (n ร n)
- All elements in the matrix are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Identify Triangles
Split matrix into bottom-left (including main diagonal) and top-right triangles
2
Classify Diagonals
Use mathematical formulas: i-j for bottom-left, i+j for top-right
3
Sort by Rules
Bottom-left diagonals: decreasing order, Top-right diagonals: increasing order
4
Reconstruct Matrix
Place sorted elements back creating the mountain peak pattern
Key Takeaway
๐ฏ Key Insight: By using mathematical properties (i-j and i+j) to identify diagonals, we can efficiently sort the matrix to create a beautiful mountain peak pattern where values decrease going down-left and increase going up-right.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code