![]() |
VOOZH | about |
Given a square matrix of order n*n, we need to print elements of the matrix in Z form
Input: [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]] Output: 4 5 6 8 3 8 1 8 7 5 Input: [[4, 5, 6, 8, 5], [1, 2, 3, 1, 4], [7, 8, 9, 4, 7], [1, 8, 7, 5, 2], [7, 9, 5, 6, 9], [9, 4, 5, 6, 6]] Output: 4 5 6 8 5 1 9 8 7 9 4 5 6 6
👁 https://media.geeksforgeeks.org/wp-content/uploads/Capture-16.png
We need to traverse the first row of the matrix then the second diagonal and then the last row.
Implementation:
4 5 6 8 3 8 1 8 7 5
Time Complexity: O(n)
Auxiliary Space: O(1)
Alternatively, we can print first row and second diagonal except last element and then last row.
4 5 6 8 3 8 1 8 7 5
Time Complexity: O(n)
Auxiliary Space: O(1)
Alternate Simpler Implementation:
Thanks to Aathishithan for suggesting this.
Implementation:
4 5 6 8 3 8 1 8 7 5
Time Complexity: O(n*n)
Auxiliary Space: O(1)