Matrix Diagonal Sum

Updated on 06 June, 2025
Matrix Diagonal Sum header image

Problem Statement

Given a square matrix referred to as mat, the task is to calculate the sum of its diagonal elements. The sum must include:

  1. All the elements on the primary diagonal which runs from the top-left corner to the bottom-right corner of the matrix.
  2. All the elements on the secondary diagonal which runs from the top-right corner to the bottom-left corner of the matrix.

For elements where the primary and secondary diagonals intersect, they should only be counted once in the sum to avoid duplication.

Examples

Example 1

Input:

mat = [[1,2,3], [4,5,6], [7,8,9]]

Output:

25

Explanation:

Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.

Example 2

Input:

mat = [[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]]

Output:

8

Example 3

Input:

mat = [[5]]

Output:

5

Constraints

  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100

Approach and Intuition

To solve this problem of summing the diagonal elements of a square matrix, we use the following approach:

  1. Iterate through each row index i from 0 to n - 1:

    • Add mat[i][i] for the primary diagonal.
    • Add mat[i][n - 1 - i] for the secondary diagonal.
  2. Avoid double-counting the center element (which lies on both diagonals) by:

    • Only adding both values in all iterations.
    • Then subtracting the center once at the end if n is odd (where i == n - 1 - i).
    • Alternatively, the addition loop already avoids double-counting naturally since it visits each index once.

This strategy yields a time complexity of O(n) and ensures all required elements are summed without duplication. The implementation is straightforward and efficient for the given constraint limits.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int sumDiagonals(vector<vector<int>>& matrix) {
        int size = matrix.size();
        int total = 0;

        for (int index = 0; index < size; index++) {
            total += matrix[index][index];
            total += matrix[size - 1 - index][index];
        }

        if (size % 2 != 0) {
            total -= matrix[size / 2][size / 2];
        }

        return total;
    }
};

The code provides a solution for calculating the sum of both the primary and secondary diagonals in a square matrix but subtracts the middle element once in the case of odd-dimension matrices, to avoid double-counting. Follow these details to understand the structure of this C++ solution:

  • A class named "Solution" is defined with a public function sumDiagonals that takes a 2D integer vector (vector<vector<int>>& matrix).
  • Initialize size to the number of rows (or columns, as it's square) of the matrix, and total as an accumulator for the sum.
  • Loop through each element index from 0 to size - 1.
    • Add the element from the primary diagonal matrix[index][index] to total.
    • Add the element from the secondary diagonal matrix[size - 1 - index][index] to total.
  • If the size of the matrix is odd, subtract the center element matrix[size / 2][size / 2] once from total to adjust for double counting.
  • Finally, the function returns the calculated total.

Ensure the supplied matrix is square to avoid any errors, as the code assumes this when accessing diagonal elements.

java
class Solution {
    public int sumDiagonals(int[][] grid) {
        int size = grid.length;
        int total = 0;

        for (int index = 0; index < size; index++) {
            total += grid[index][index]; // Primary diagonal
            total += grid[size - 1 - index][index]; // Secondary diagonal
        }
        if (size % 2 != 0) { // Adjust for center element in odd-sized grid
            total -= grid[size / 2][size / 2];
        }

        return total;
    }
}

This solution efficiently calculates the sum of two diagonals in a square matrix in Java. The provided class, Solution, includes a method sumDiagonals that computes the sum of the primary and secondary diagonals of a given matrix.

Here's how the algorithm works:

  1. Initialize size to the length of one side of the square matrix.
  2. Initialize total to 0 to keep track of the running sum of diagonal elements.

The method performs a single loop over the matrix:

  1. Loop through each index from 0 to size - 1:

    • Add the element from the primary diagonal at grid[index][index] to total.
    • Add the element from the secondary diagonal at grid[size - 1 - index][index] to total.
  2. For matrices with an odd size, the central element is counted twice (once in each diagonal). Adjust for this by subtracting the central element, grid[size / 2][size / 2], from total if the matrix size is odd.

  3. Finally, return total, which now contains the sum of all the elements in both diagonals, adjusted for the central element in odd-sized matrices.

This method provides a clear and concise approach to calculate diagonal sums with optimal performance, making it suitable for matrices of any size.

python
class Solution:
    def diagonalSum(self, matrix: List[List[int]]) -> int:
        size = len(matrix)
        total = 0

        for idx in range(size):
            # Summing the main diagonal elements
            total += matrix[idx][idx]
            # Summing the secondary diagonal elements
            total += matrix[size - 1 - idx][idx]
        # Correcting the center element if size is odd, as it gets added twice
        if size % 2 == 1:
             total -= matrix[size // 2][size // 2]
        
        return total

To calculate the sum of both the primary and secondary diagonals in a matrix, ensure to adjust for any overlapping elements if the matrix is of odd size and has a middle element in the diagonal intersection. Implement the following steps in Python:

  1. Initialize a variable size to the length of the matrix to represent its dimension, assuming that the matrix is square (equal number of rows and columns).
  2. Create a total variable set to zero, which will store the sum of the diagonal elements.
  3. Use a loop to iterate over the indices idx of the matrix from 0 to size-1. In each iteration:
    • Add the element at the main diagonal matrix[idx][idx] to total.
    • Add the element at the secondary diagonal matrix[size - 1 - idx][idx] to total.
  4. After the loop, check if the matrix size is odd (use size % 2 == 1). If true, subtract the value of the center element matrix[size // 2][size // 2] from the total since it is counted twice (once in each diagonal).

This solution efficiently computes the desired sum in a single pass through the main and secondary diagonals of the matrix, correcting for any potential overlap in constant time.

Comments

No comments yet.