Program to find diagonal sum of a matrix in Python

A square matrix has two main diagonals: the primary diagonal (from top-left to bottom-right) and the secondary diagonal (from top-right to bottom-left). To find the diagonal sum, we add all elements from both diagonals while avoiding double-counting the center element in odd-sized matrices.

Problem Example

Consider this 4×4 matrix ?

10 5 9 6
8 15 3 2
3 8 12 3
2 11 7 3

The primary diagonal elements are [10, 15, 12, 3] with sum = 40. The secondary diagonal elements are [6, 3, 8, 2] with sum = 19. Total diagonal sum = 40 + 19 = 59.

Algorithm Steps

To solve this problem, follow these steps ?

  • Get the matrix size (m = number of rows)

  • If matrix is 1×1, return the single element

  • Initialize count = 0

  • For each row i from 0 to m-1:

    • Add primary diagonal element: matrix[i][i]

    • Add secondary diagonal element: matrix[i][m-1-i]

  • If matrix size is odd, subtract the center element (counted twice)

  • Return the total count

Implementation

def diagonal_sum(matrix):
    m = len(matrix)
    if m == 1: 
        return matrix[0][0]

    count = 0
    for i in range(m):
        count += matrix[i][i]           # Primary diagonal
        count += matrix[i][m - 1 - i]   # Secondary diagonal

    # Subtract center element if matrix size is odd (to avoid double counting)
    if m % 2 == 1: 
        count -= matrix[m // 2][m // 2]

    return count

# Test with the example matrix
matrix = [[10, 5, 9, 6], [8, 15, 3, 2], [3, 8, 12, 3], [2, 11, 7, 3]]
result = diagonal_sum(matrix)
print(f"Diagonal sum: {result}")

# Test with a 3x3 odd matrix
matrix_odd = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result_odd = diagonal_sum(matrix_odd)
print(f"Diagonal sum (3x3): {result_odd}")
Diagonal sum: 59
Diagonal sum (3x3): 25

How It Works

The algorithm iterates through each row and adds both diagonal elements simultaneously. For the primary diagonal, we access matrix[i][i]. For the secondary diagonal, we access matrix[i][m-1-i] where m-1-i gives us the column index that decreases as the row index increases.

In odd-sized matrices, the center element matrix[m//2][m//2] lies on both diagonals, so we subtract it once to avoid double-counting.

Conclusion

This solution efficiently calculates the diagonal sum in O(n) time by traversing the matrix once. The key insight is handling the center element correctly in odd-sized matrices to avoid double-counting.

Updated on: 2026-03-25T20:21:00+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements