Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals.
Input : 1 2 1 4 5 2 0 5 1 Output : 2 Primary diagonal is 1 5 1 Secondary diagonal is 1 5 0 Two elements (1 and 5) match in two diagonals and same. Input : 1 0 0 0 1 0 0 0 1 Output : 1 Primary diagonal is 1 1 1 Secondary diagonal is 0 1 0 Only one element is same.
We can achieve this in O(n) time, O(1) space and only one traversal. We can find current element in i-th row of primary diagonal as mat[i][i] and i-th element of secondary diagonal as mat[i][n-i-1].
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sort Matrix in alternating ascending and descending order rowwise
- Find the product of sum of two diagonals of a square Matrix
- Sum of both diagonals of a spiral odd-order square matrix
- Swap major and minor diagonals of a square matrix
- Find smallest and largest element from square matrix diagonals
- Finding the converging element of the diagonals in a square matrix
- Sum of all parts of a square Matrix divided by its diagonals
- Return an array of anti-diagonals of given N*N square matrix
- Create matrix whose sum of diagonals in each sub matrix is even
- Program to Interchange Diagonals of Matrix
- Efficiently compute sums of diagonals of a matrix
- Center element of matrix equals sums of half diagonals
- Number of cells in the right and left diagonals passing through (x, y) in a matrix
- Program to print the Diagonals of a Matrix in O(N) time
- Program to print the Diagonals of a Matrix
- Find difference between sums of two diagonals
- Check if matrix can be converted to another matrix by transposing square sub-matrices
- Construct a square Matrix whose parity of diagonal sum is same as size of matrix
- Common elements in all rows of a given matrix
- Find distinct elements common to all rows of a matrix