Given an M × N integer matrix, print all its diagonal elements having a positive slope.

For example,

Input:
 
Diagonal Matrix
 
Output:
 
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6
7 7 7
8 8
9

Practice this problem

The idea is to start from each cell of the first column of the matrix to print / diagonal for the matrix’s upper-left half. Similarly, after the upper-left half, start from each cell of the last row to print the / diagonal for the matrix’s lower-right half.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6
7 7 7
8 8
9

The time complexity of the proposed solution is O(M × N) for an M × N matrix and doesn’t require any extra space.