Skip to main content

Matrix Diagonal Sum Solution

In this page, we will solve the Matrix Diagonal Sum problem using multiple approaches. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++.

Problem Description​

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

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

Example 2:

Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Explanation: Diagonals sum: 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8

Constraints​

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

Solution for Matrix Diagonal Sum Problem​

Intuition and Approach​

We can solve this problem by iterating over the matrix and summing up the elements on both diagonals.

Approach: Iterative​

In this approach, we iterate through the matrix and add elements from the primary diagonal and the secondary diagonal.

Implementation​

Live Editor
function matrixDiagonalSum() {
  const mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];

  const diagonalSum = function(mat) {
    let sum = 0;
    const n = mat.length;
    for (let i = 0; i < n; i++) {
      sum += mat[i][i]; // Primary diagonal
      if (i !== n - 1 - i) { // Exclude middle element for odd-sized matrix
        sum += mat[i][n - 1 - i]; // Secondary diagonal
      }
    }
    return sum;
  };

  const result = diagonalSum(mat);
  return (
    <div>
      <p>
        <b>Input:</b> mat = {JSON.stringify(mat)}
      </p>
      <p>
        <b>Output:</b> {result}
      </p>
    </div>
  );
}
Result
Loading...

Codes in Different Languages​

Written by @manishh12
 function diagonalSum(mat) {
let sum = 0;
const n = mat.length;
for (let i = 0; i < n; i++) {
sum += mat[i][i]; // Primary diagonal
if (i !== n - 1 - i) { // Exclude middle element for odd-sized matrix
sum += mat[i][n - 1 - i]; // Secondary diagonal
}
}
return sum;
}

Complexity Analysis​

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)
  • Where n is the size of the square matrix mat.
  • The time complexity is linear because we iterate through the matrix only once.
  • The space complexity is constant as we use only a few variables irrespective of the size of the input.
Note

By using these approaches, we can efficiently solve the Matrix Diagonal Sum problem for the given constraints.

References​