File: matrix-diagonal-sum/solution.py

Date: 2026-06-06

Time: 17:32

matrix-diagonal-sum/solution.py

Purpose

This file solves LeetCode 1572 — Matrix Diagonal Sum. It computes the sum of both diagonals of an n x n square matrix, ensuring the center element (when n is odd) is counted only once.

Key Components

Solution.diagonalSum(mat: List[List[int]]) -> int — The sole method. Takes a square matrix and returns the sum of all elements on the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left).

Flow

1. Single-pass accumulation: Iterates i from 0 to n-1. At each step, adds two elements:

2. Center correction: When n is odd, both diagonals share the center element at (n//2, n//2). The loop double-counts it, so it's subtracted once after the loop.

This is an O(n) time, O(1) space solution — it touches each diagonal element exactly once (with one subtraction to fix the overlap).

Patterns

Dependencies

Invariants

Error Handling

None. The function trusts its input matches the problem constraints. An empty matrix (n=0) would return 0 without error, which is arguably correct.

Topics to Explore

Beliefs