Sort the Matrix Diagonally

A matrix diagonal is the line of cells that starts at a cell in the top row or the left column and moves down and to the right until it leaves the matrix. Given an m x n matrix mat of integers, sort every matrix diagonal in ascending order and return the resulting matrix.

30:00

Sort the Matrix Diagonally
medium
Free written solution
Topics
Companies

A matrix diagonal is the line of cells that starts at a cell in the top row or the left column and moves down and to the right until it leaves the matrix. Given an m x n matrix mat of integers, sort every 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]]
Constraints:
  • m=mat.lengthm = \text{mat.length}

  • n=mat[i].lengthn = \text{mat}[i]\text{.length}

  • 1≤m,n≤1001 \leq m, n \leq 100

  • 1≤mat[i][j]≤1001 \leq \text{mat}[i][j] \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"mat":[[3,3,1,1],[2,2,1,2],[1,1,1,2]]}

A 3 x 4 matrix has 6 diagonals running down and to the right. Each one is sorted on its own, smallest value at the top-left.

matrix, one diagonal at a time

3
3
1
1
2
2
1
2
1
1
1
2

lifted diagonal

No diagonal lifted yet.

sorted diagonals: 0 / 6

Variables
VariableValue
m3
n4
diagonals6
DepthFunction Call
Stack empty
0/21