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
๐Ÿ”๏ธ Mountain Peak Matrix VisualizationPeak(Main Diagonal)Decreasing โ†™Increasing โ†—Matrix TransformationBefore312574869โ†’After912674553๐ŸŽฏ Key Insight: Mathematical diagonal classification enables efficient sorting in O(nยฒ log n)
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen