Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].
Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Example 2:
Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 1001 <= mat[i][j] <= 100Problem summary: A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[3,3,1,1],[2,2,1,2],[1,1,1,2]]
[[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
sort-matrix-by-diagonals)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1329: Sort the Matrix Diagonally
class Solution {
public int[][] diagonalSort(int[][] mat) {
int m = mat.length, n = mat[0].length;
List<Integer>[] g = new List[m + n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
g[m - i + j].add(mat[i][j]);
}
}
for (var e : g) {
Collections.sort(e, (a, b) -> b - a);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
mat[i][j] = g[m - i + j].removeLast();
}
}
return mat;
}
}
// Accepted solution for LeetCode #1329: Sort the Matrix Diagonally
func diagonalSort(mat [][]int) [][]int {
m, n := len(mat), len(mat[0])
g := make([][]int, m+n)
for i, row := range mat {
for j, x := range row {
g[m-i+j] = append(g[m-i+j], x)
}
}
for _, e := range g {
sort.Sort(sort.Reverse(sort.IntSlice(e)))
}
for i, row := range mat {
for j := range row {
k := len(g[m-i+j])
mat[i][j] = g[m-i+j][k-1]
g[m-i+j] = g[m-i+j][:k-1]
}
}
return mat
}
# Accepted solution for LeetCode #1329: Sort the Matrix Diagonally
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
g = [[] for _ in range(m + n)]
for i, row in enumerate(mat):
for j, x in enumerate(row):
g[m - i + j].append(x)
for e in g:
e.sort(reverse=True)
for i in range(m):
for j in range(n):
mat[i][j] = g[m - i + j].pop()
return mat
// Accepted solution for LeetCode #1329: Sort the Matrix Diagonally
impl Solution {
pub fn diagonal_sort(mut mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let m = mat.len();
let n = mat[0].len();
let mut g: Vec<Vec<i32>> = vec![vec![]; m + n];
for i in 0..m {
for j in 0..n {
g[m - i + j].push(mat[i][j]);
}
}
for e in &mut g {
e.sort_by(|a, b| b.cmp(a));
}
for i in 0..m {
for j in 0..n {
mat[i][j] = g[m - i + j].pop().unwrap();
}
}
mat
}
}
// Accepted solution for LeetCode #1329: Sort the Matrix Diagonally
function diagonalSort(mat: number[][]): number[][] {
const [m, n] = [mat.length, mat[0].length];
const g: number[][] = Array.from({ length: m + n }, () => []);
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
g[m - i + j].push(mat[i][j]);
}
}
for (const e of g) {
e.sort((a, b) => b - a);
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
mat[i][j] = g[m - i + j].pop()!;
}
}
return mat;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.