Write a Program to Print the Diagonal Elements of the Given 2D MatrixIn this tutorial, we will write the Python program to print the diagonal elements of the given matrix. It is a common program that can be asked in technical interviews. A 2D matrix is given; we need to print the primary and secondary diagonals. Input: Output: Primary Diagonal: 1, 3, 9, 3 Secondary Diagonal: 4, 2, 8, 6 Input: Output: Primary Diagonal: 2, 2, 2 Secondary Diagonal: 2, 2, 2 Let's understand the row-column pattern of the matrix in Python.
Output: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Matrix Representation in PythonRemember that we always put the row number first and then the column number. The correct format of an element X inside a matrix becomes X (R, C), where R and C represent the row and column where the element is present. Let's see the following 3x3 and 2x2 matrixes of numbers, and Z represents a 2X3 matrix of string. Example - Output: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] [[27, 34], [61, 18]] [['one', 'two', 'three'], ['four', 'five', 'six']] Now we have the basic idea of the matrix presentation in Python. Now let's jump to the solution part. SolutionLet's understand the first method. Method - 1: In this method, we will use the two for loops for columns and a loop for rows, and in the inner loop, we check for the condition. Example - Output: Primary Diagonal is: 1,3,9,3, Explanation - In the above code, we get the rows and col of and matrix and we have used the two for loops. In the inner loop, we checked the conditions if the i and j are equal than print the corresponding element. Now we will write Program to get the secondary diagonal Example - 2: Output: Secondary Diagonal: 4, 2, 8, 6, Time Complexity - O(n2) As there is a nested loop involved so the time complexity is squared. Auxiliary Space: O(1). As no extra space is occupied Method - 2: We can solve this problem using the single for loop. Let's understand the following example. Example - Output: Principal Diagonal: 1, 6, 3, 8, Explanation - In the above code, we run a for loop until length of matrix n, and print the mat[i][i] where i is the index variable. For Secondary Diagonal Elements Example - 2: Output: Secondary Diagonal: 4, 7, 2, 1, Explanation - We have used the same approach as above and print mat[i][k] where i is the index variable and k = matrix_length - 1 and decrease k until i < n. Complexity Analysis:
Next TopicEncapsulation in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India