#1572

Matrix Diagonal Sum

Easy
ArrayMatrixTwo PointersSliding WindowMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution is similar to the brute force approach but focuses on reducing unnecessary operations. We can calculate both diagonal sums in a single loop, making it more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to hold the sum of the diagonals.
  2. 2Step 2: Loop through each row of the matrix, adding the primary and secondary diagonal elements in one pass.
  3. 3Step 3: If the matrix size is odd, subtract the middle element once.
  4. 4Step 4: Return the total sum.
solution.py9 lines
1def diagonalSum(mat):
2    n = len(mat)
3    total_sum = 0
4    for i in range(n):
5        total_sum += mat[i][i]  # Primary diagonal
6        total_sum += mat[i][n - 1 - i]  # Secondary diagonal
7    if n % 2 == 1:
8        total_sum -= mat[n // 2][n // 2]  # Subtract the middle element if odd
9    return total_sum

Complexity note: The time complexity is O(n) because we only loop through the matrix once, and the space complexity is O(1) since we are using a constant amount of extra space.

  • 1The primary diagonal consists of elements where row index equals column index.
  • 2The secondary diagonal consists of elements where the column index is the reverse of the row index.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.