Sort the Matrix Diagonally (LeetCode 1329): Solution and Explanation

Medium
Array
Sorting
Matrix

Given an m x n matrix, sort every down-right diagonal so its values increase from the top-left end to the bottom-right end, and return the matrix.

Intuition

A down-right diagonal is the set of cells with the same j - i. Two different diagonals never share a cell, so sorting one never disturbs another.

Each diagonal starts on the boundary: either in column 0 (one per row) or in row 0 (one per column after the first). That gives exactly m + n - 1 diagonals to visit.

Sorting a diagonal in place is awkward because its cells are not contiguous in memory. The easy path is to copy its values into a plain list, sort that list, and copy them back along the same path.

Approach: Lift, sort, write back

  1. For every row r, process the diagonal that starts at (r, 0). For every column c from 1, process the diagonal that starts at (0, c).
  2. The diagonal from (r, c) has min(m - r, n - c) cells. Read mat[r + k][c + k] for each k into a list.
  3. Sort the list in ascending order.
  4. Write the sorted values back: mat[r + k][c + k] = vals[k].
  5. Return the matrix once all diagonals are done.

Step-by-step example

mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
  1. The matrix is 3 x 4, so there are 3 + 4 - 1 = 6 diagonals.
  2. Diagonal from (0,0): values 3, 2, 1. Sorted: 1, 2, 3, written back to (0,0), (1,1), (2,2).
  3. Diagonal from (1,0): values 2, 1. Sorted: 1, 2. Diagonal from (2,0) is the single cell 1.
  4. Diagonal from (0,1): values 3, 1, 2. Sorted: 1, 2, 3. Diagonal from (0,2): values 1, 2, already sorted. Diagonal from (0,3) is the single cell 1.
  5. The result is [[1,1,1,1],[1,2,2,2],[1,2,3,3]].

Code: Python, Java, C++

1class Solution:
2    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
3        m, n = len(mat), len(mat[0])
4        for r in range(m):
5            self.sortDiagonal(mat, r, 0)
6        for c in range(1, n):
7            self.sortDiagonal(mat, 0, c)
8        return mat
9
10    def sortDiagonal(self, mat: List[List[int]], r: int, c: int) -> None:
11        length = min(len(mat) - r, len(mat[0]) - c)
12        vals = [mat[r + k][c + k] for k in range(length)]
13        vals.sort()
14        for k in range(length):
15            mat[r + k][c + k] = vals[k]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n * log(min(m, n)))

Every cell is read and written once, and each diagonal has at most min(m, n) cells, so sorting it costs at most O(min(m, n) log min(m, n)) per cell group.

Space

O(min(m, n))

Only one diagonal's values are held in the temporary list at a time.

Other approaches

Heaps keyed by i - j (time O(m * n * log(min(m, n))), space O(m * n))

Push every value into a min-heap for its diagonal key i - j, then walk the matrix in row order and pop from the matching heap. Popping in row order hands out the smallest remaining value first, which fills each diagonal in sorted order.

Counting sort per diagonal (time O(m * n + (m + n) * 100), space O(100))

Values are limited to 1..100, so a 101-slot count array per diagonal replaces the comparison sort. Each diagonal costs O(d + 100) instead of O(d log d).

Common mistakes

  • Visiting the corner diagonal twice. If you loop rows from 0 and columns from 0, the diagonal at (0,0) is processed twice; start the column loop at 1.
  • Using the wrong length. The diagonal from (r, c) has min(m - r, n - c) cells, not min(m, n).
  • Sorting as strings in JavaScript. Array.prototype.sort with no comparator compares text, so 10 sorts before 9; pass (a, b) => a - b.
  • Grouping by i + j. That key groups anti-diagonals (down-left), not the down-right diagonals this problem asks for.

Frequently asked questions

Why can each diagonal be sorted independently?

Every cell belongs to exactly one down-right diagonal, identified by j - i. Sorting one diagonal only rewrites its own cells, so the order you process them in does not matter.

How many diagonals does an m x n matrix have?

m + n - 1. There is one starting in each row of column 0, plus one starting in each column of row 0 except column 0, which was already counted.

Is the result unique?

Yes. Each diagonal holds a fixed multiset of values, and there is only one way to arrange a multiset in ascending order.