[LeetCode] Sort Matrix by Diagonals

3446. Sort Matrix by Diagonals

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
"sort"
)

func sortMatrix(grid [][]int) [][]int {
n := len(grid)

for x := 0; x < n; x++ {
var r, c []int

for i, j := x, 0; i < n && j < n; i, j = i+1, j+1 {
r = append(r, grid[i][j])
}
for i, j := 0, x; i < n && j < n; i, j = i+1, j+1 {
c = append(c, grid[i][j])
}

sort.Sort(sort.Reverse(sort.IntSlice(r)))
sort.Ints(c)

for i, j := 0, x; i < n && j < n; i, j = i+1, j+1 {
grid[i][j] = c[i]
}
for i, j := x, 0; i < n && j < n; i, j = i+1, j+1 {
grid[i][j] = r[j]
}
}

return grid
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/09/PS/LeetCode/sort-matrix-by-diagonals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.