Sort 2D Matrix Diagonally | Coding Interview | Matrix | Sorting

Ganesh Prasad
3 min readJan 8, 2022

In this article, I have explained the solution for this problem in simple terms.

Sorting the matrix of size m x n diagonally.

The approach is very simple; we have to put elements of each diagonal in a list or some other collection (we will discuss it later), then sort them and put them back in the same diagonal.

Fig 1. put each diagonal into a list and sort them before putting them back in the matrix.

This article is part of the following preparation plan.

The question is how to access each element of a particular diagonal? And the answer to this problem is that each diagonal in a matrix has a unique I.D. Take any element A[i][j] of a diagonal, then (i-j) is the unique I.D. for that diagonal. In other words, every element A[i][j] of matrix A belongs to the diagonal with the I.D. of i-j.

--

--

Ganesh Prasad

Backend Developer at Appscrip | C++ veteran, 💜 Dart