VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-matrix-diagonally-downwards/

⇱ Print the matrix diagonally downwards - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the matrix diagonally downwards

Last Updated : 3 Apr, 2026

Given a 2D mat of size n*n, print the matrix in the following pattern.

Examples:

Input: n = 2, mat[][] = [[1, 2],
[3, 4]]
Output: [1, 2, 3, 4]
Explanation:
👁 Image

Input: n = 3, mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: [1, 2, 4, 3, 5, 7, 6, 8, 9]
Explanation:
👁 Image

[Naive Approach] Using Brute Force - O(n*n) Time and O(n*n) Space

The idea is to use the value of i + j, since elements with the same value lie on the same diagonal. We create a temporary array of arrays and store same diagonal elements at one place using (i+j) as index. Finally iterate over the temporary array to print the items diagonally.


Output
1 2 4 3 5 7 6 8 9 

[Expected Approach] Using Direct Diagonal Traversal - O(n*n) Time and O(1) Space

Traverse each diagonal directly by starting from every element in the first row and then from every element in the last column (Except the first element of the last column). From each starting point, move diagonally (down-left) and print elements until going out of bounds.

  • We first print diagonals beginning with first row elements (1, 2, 3 & 4)
  • Then we print diagonals with the last column elements starting from 2nd (8, 12 & 16)
👁 Image

Output
1 2 4 3 5 7 6 8 9 
Comment
Article Tags:
Article Tags: