Matrix Diagonal Sum

Matrix Diagonal Sum

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.

LeetCode Problem - 1572

class Solution {
    // Method to calculate the sum of the diagonals of a matrix
    public int diagonalSum(int[][] mat) {
        // Initialize variables to track indices of the left and right diagonals
        int lDiagonalrow = 0;  // Start index for left diagonal row
        int lDiagonalCol = 0;  // Start index for left diagonal column
        int rDiagonalrow = 0;  // Start index for right diagonal row
        int rDiagonalCol = mat.length - 1;  // Start index for right diagonal column
        int answer = 0;  // Variable to store the sum of diagonal elements

        // Iterate through each row of the matrix
        for (int i = 0; i < mat.length; i++) {
            // Check if matrix length is odd
            if (mat.length % 2 != 0) {
                // Check if we are not at the center element (for odd-sized matrix)
                if (!(lDiagonalrow == lDiagonalCol && lDiagonalCol == rDiagonalrow && rDiagonalrow == rDiagonalCol)) {
                    // Add elements from both diagonals to answer
                    int val1 = mat[lDiagonalrow][lDiagonalCol];
                    int val2 = mat[rDiagonalrow][rDiagonalCol];
                    answer += val1;
                    answer += val2;
                } else {
                    // Add element from left diagonal only (center element for odd-sized matrix)
                    int val1 = mat[lDiagonalrow][lDiagonalCol];
                    answer += val1;
                }
            } else {
                // Add elements from both diagonals to answer (for even-sized matrix)
                int val1 = mat[lDiagonalrow][lDiagonalCol];
                int val2 = mat[rDiagonalrow][rDiagonalCol];
                answer += val1;
                answer += val2;
            }

            // Move to the next elements in both diagonals
            lDiagonalrow++;
            lDiagonalCol++;
            rDiagonalrow++;
            rDiagonalCol--;
        }

        // Return the sum of diagonal elements
        return answer;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!