VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-diagonals-spiral-odd-order-square-matrix/

⇱ Sum of both diagonals of a square matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of both diagonals of a square matrix

Last Updated : 7 Jun, 2026

Given a square matrix of size n * n. Your task is to calculate the sum of its diagonals. When n is odd, there is a center value which is counted twice in the diagonal sum.

Examples :

Input: mat[][] = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]

👁 blobid5_1777722491

Output: 6
Explanation: Sum of primary diagonal (3) and secondary diagonal (3) is 6, where the center element is counted twice.

Input: mat[][] = [[1, 2], [3, 4]]

👁 blobid1_1777714129

Output: 10
Explanation: Sum of primary diagonal (5) and secondary diagonal (5) is 10.

[Naive Approach] Traverse Entire Matrix - O(n^2) Time O(1) Space

The idea is to traverse every cell of the matrix and separately check whether it belongs to the primary diagonal or the secondary diagonal. Since the checks are performed independently, the center element of an odd-sized matrix gets counted twice, as required by the problem.


Output
10

Time Complexity: O(n^2)
Auxiliary Space: O(1)

[Expected Approach] Traverse Only Diagonals - O(n) Time O(1) Space

The idea is to iterate through each row and directly add the primary diagonal element mat[i][i] and the secondary diagonal element mat[i][n-i-1]. For odd-sized matrices, the center element naturally gets counted twice as required.

Let us understand with example:
Input: mat[][] = [[1, 2], [3, 4]]

  • Initially, sum = 0.
  • First loop adds primary diagonal elements: sum = 0 + 1 + 4 = 5
  • Second loop adds secondary diagonal elements: sum = 5 + 2 + 3 = 10
  • So, the final diagonal sum is 10.

Output
10

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: