Print squares of diagonal elements in O(n) time complexity
Input: 1 2 3
4 5 6
7 8 9
Output: 1 25 81
9 25 49
public class SquareOfDiagonal { static void printDiagonalSquare(int[][] mat) { int n = mat.length; int principalDig[] = new int[n]; int secondaryDig[] = new int[n]; for (int i = 0; i < mat.length; i++) { principalDig[i] = mat[i][i] * mat[i][i]; secondaryDig[i] = mat[i][n - i - 1] * mat[i][n - i - 1]; } for (int i = 0; i < n; i++) { System.out.print(principalDig[i] + " "); } System.out.println(); for (int i = 0; i < n; i++) { System.out.print(secondaryDig[i] + " "); } } static public void main(String[] args) { int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; printDiagonalSquare(a); } }
Thanks and Regards,
Solution provided by Nilmani Prashanth