Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1572: Matrix Diagonal Sum

ArrayMatrix

LeetCode 1572 Solution Explanation

Explanation

To solve this problem, we need to iterate through the elements of the given square matrix and calculate the sum of the primary diagonal and the secondary diagonal excluding the overlapping element. We can achieve this by maintaining two pointers for the primary diagonal and the secondary diagonal. We iterate through the matrix and update the sum based on the current element's position.

  • For the primary diagonal, the indices of the elements are when i == j.
  • For the secondary diagonal, the indices of the elements are when i + j == n - 1, where n is the size of the matrix.

After calculating the sum of both diagonals, we return the total sum as the result.

Time Complexity: O(n), where n is the size of the matrix. Space Complexity: O(1)

LeetCode 1572 Solutions in Java, C++, Python

class Solution {
    public int diagonalSum(int[][] mat) {
        int n = mat.length;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += mat[i][i]; // primary diagonal
            sum += mat[i][n - 1 - i]; // secondary diagonal
        }
        if (n % 2 == 1) {
            sum -= mat[n/2][n/2]; // Exclude the middle element if the matrix has an odd size
        }
        return sum;
    }
}

Interactive Code Editor for LeetCode 1572

Improve Your LeetCode 1572 Solution

Use the editor below to refine the provided solution for LeetCode 1572. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems