You are currently viewing Interview program – Matrix

Interview program – Matrix

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

Partners: neteller funky time live game casino ohne einsatzlimit 0x.bet Casino online casino uden rofus paypal maksu ei onnistu zimpler sportsbooks netticasino tarjoukset Rabona Casino casino minimitalletus 10

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply