VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-difference-between-sums-of-two-diagonals/

⇱ Find difference between sums of two diagonals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find difference between sums of two diagonals

Last Updated : 23 Jul, 2025

Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.

Examples: 

Input : mat[][] = 11 2 4
 4 5 6
 10 8 -12 
Output : 15
Sum of primary diagonal = 11 + 5 + (-12) = 4.
Sum of secondary diagonal = 4 + 5 + 10 = 19.
Difference = |19 - 4| = 15.


Input : mat[][] = 10 2
 4 5
Output : 9

Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along the other diagonal, row index = n - 1 - column index i.e mat[i][j] lies on the second diagonal if i = n-1-j. By using two loops we traverse the entire matrix and calculate the sum across the diagonals of the matrix.

Below is the implementation of this approach: 


Output
15

Time complexity: O(n*n)
Auxiliary Space: O(1) using constant space to initialize diagonal sums, since no extra space has been taken.

We can optimize the above solution to work in O(n) using the patterns present in indexes of cells. 


Output
15

Time complexity : O(n)
Auxiliary Space: O(1) using constant space to initialize diagonal sums

Comment
Article Tags:
Article Tags: