Matrix Diagonal Sum (LeetCode 1572): Solution and Explanation
Given a square matrix, add up the values on both diagonals. A cell that sits on both diagonals, which only happens at the centre of an odd-sized matrix, is counted once.
Intuition
You do not need to scan the whole matrix. Each row contains exactly one cell of the primary diagonal and exactly one cell of the secondary diagonal, so the work is one loop over the rows.
In row i the primary cell is in column i, and the secondary cell is in column n - 1 - i because that diagonal runs from the right edge back to the left.
The two columns collide only when i equals n - 1 - i, which is the middle row of an odd-sized matrix. There the same cell would be added twice, so you add it once and skip the second add.
Approach: One pass over the rows
- Set
total = 0andn = len(mat). - For each row
i, addmat[i][i]tototal. - If
i != n - 1 - i, also addmat[i][n - 1 - i]. - Return
totalafter the last row.
Step-by-step example
mat = [[1,2,3],[4,5,6],[7,8,9]]
- total = 0.
- Row 0: add mat[0][0] = 1 and mat[0][2] = 3, total = 4.
- Row 1: add mat[1][1] = 5, total = 9. Column n-1-1 is also 1, so the centre is not added again.
- Row 2: add mat[2][2] = 9 and mat[2][0] = 7, total = 25.
- Return 25.
Code: Python, Java, C++
1class Solution:
2 def diagonalSum(self, mat: List[List[int]]) -> int:
3 n = len(mat)
4 total = 0
5 for i in range(n):
6 total += mat[i][i]
7 if i != n - 1 - i:
8 total += mat[i][n - 1 - i]
9 return total1class Solution {
2 public int diagonalSum(int[][] mat) {
3 int n = mat.length;
4 int total = 0;
5 for (int i = 0; i < n; i++) {
6 total += mat[i][i];
7 if (i != n - 1 - i) {
8 total += mat[i][n - 1 - i];
9 }
10 }
11 return total;
12 }
13}1class Solution {
2public:
3 int diagonalSum(vector<vector<int>>& mat) {
4 int n = mat.size();
5 int total = 0;
6 for (int i = 0; i < n; i++) {
7 total += mat[i][i];
8 if (i != n - 1 - i) {
9 total += mat[i][n - 1 - i];
10 }
11 }
12 return total;
13 }
14};Time and space complexity
O(n)
One loop over n rows with at most two additions each.
O(1)
Only the running total and the loop index are stored.
Other approaches
Add both, then subtract the centre (time O(n), space O(1))
Always add both diagonal cells in every row, then subtract mat[n/2][n/2] once at the end if n is odd. Same cost, and some people find it easier to remember.
Scan every cell (time O(n^2), space O(1))
Loop over all cells and add the ones where i == j or i + j == n - 1. The or handles the centre naturally, but it reads n squared cells instead of 2n.
Common mistakes
- Counting the centre cell twice when
nis odd. - Subtracting the centre when
nis even, where there is no shared cell. - Using column
n - iinstead ofn - 1 - ifor the secondary diagonal, which reads past the end of the row.
Frequently asked questions
When do the two diagonals share a cell?
Only when n is odd. The shared cell is the exact centre, mat[n/2][n/2], where i equals n - 1 - i.
Why is the secondary column n - 1 - i?
That diagonal starts at the top-right corner, column n - 1, and moves one column left for every row down, so in row i it is at n - 1 - i.
What is the time complexity of Matrix Diagonal Sum?
O(n), because each of the n rows contributes at most two cells. No extra memory is needed.