VOOZH about

URL: https://www.geeksforgeeks.org/dsa/squares-of-matrix-diagonal-elements/

⇱ Squares of Matrix Diagonal Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Squares of Matrix Diagonal Elements

Last Updated : 21 Dec, 2024

Given an integer matrix mat[][] of odd dimensions, the task is to find the square of the elements of the Primary and Secondary diagonals.

The Primary and Secondary diagonal matrix explanation is given below:

  • Primary Diagonal Elements of a Matrix: The Primary Diagonal Elements are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. The Primary Diagonal is also known as Main Diagonal or Major Diagonal.
  • Secondary Diagonal Elements of a Matrix: The Secondary Diagonal Elements are the ones that occur from Top Right of Matrix Down To Bottom Left Corner. Also known as Minor Diagonal.

Examples:

Input:
mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Output: 1 25 81
9 25 49

Explanation: Principal Diagonal: {1, 5, 9}, on squaring each element we will get {1, 25, 81}. Secondary Diagonal: {3, 5, 7}, on squaring each element we will get {9, 25, 49}

Input:
mat[][] = [[8]]

Output: 64
64

Explanation: Principal Diagonal: {8}, on squaring each element we will get {64}. Secondary Diagonal: {8}, on squaring each element we will get {64}

[Naive Approach] By traversing on all elements - O(m*n) Time and O(1) Space

The idea is to traverse the matrix in row-column fashion using the nested loops. The outer loop i is used to traverse all the rows and inner loop j is used traverse all the columns of each row. For each index in the matrix, if i == j, it corresponds to the principal diagonal and if i == n-j-1, it corresponds to the secondary diagonal, where n is the count of columns in each row of the matrix. Traverse the matrix twice, firstly for principal diagonal and then for secondary diagonal. For each element of any of the diagonal, print the square of its value.


Output
1 25 81 
9 25 49 

[Efficient Approach] By traversing only on diagonal elements - O(n) Time and O(1) Space

Each row in a matrix has only one diagonal element. Instead of checking every column, we can directly calculate the diagonal indices. For the primary diagonal, row and column indices are equal, so we print the square of mat[i][i]. For the secondary diagonal, the column index is n - i - 1, where n is the number of columns, so we can print square of mat[i][n-i-1].


Output
1 25 81 
9 25 49 
Comment
Article Tags:
Article Tags: