Easiest JAVA Solution for Beginners [ 100% ] [ 0ms ]
Approach\n1. Initialize Variables:\n   - Initialize sum to 0 to store the sum of diagonal elements.\n   - Get the number of rows and columns from the matrix dim
# Approach\n1. **Initialize Variables:**\n   - Initialize `sum` to 0 to store the sum of diagonal elements.\n   - Get the number of rows and columns from the matrix dimensions.\n\n2. **Sum Primary Diagonal:**\n   - Loop through the matrix using a single index `i` from 0 to `row - 1`.\n   - Add the element `mat[i][i]` (primary diagonal) to `sum`.\n\n3. **Sum Secondary Diagonal:**\n   - Loop through the matrix using indices `i` from 0 to `row - 1` and `j` from `col - 1` to 0.\n   - Check if the current element `mat[i][j]` is already included (i.e., `i == j`).\n   - If not included, add `mat[i][j]` (secondary diagonal) to `sum`.\n\n4. **Return Result:**\n   - Return the value of `sum` which contains the sum of both primary and secondary diagonal elements, avoiding double-counting the center element if the matrix has an odd dimension.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int sum=0, row=mat.length, col=mat[0].length;\n        for(int i=0, j=0; i<row; i++, j++){\n            sum+=mat[i][j];\n        }\n        for(int i=0, j=col-1; i<row && j>=0; i++, j--){\n            if(i==j) continue;\n            sum+=mat[i][j];\n        }\n        return sum;\n    }\n}\n```\n\n![193730892e8675ebafc11519f6174bee5c4a5ab0.jpeg](https://assets.leetcode.com/users/images/1a1e89cb-d54b-477f-a91e-64f71c201745_1718520004.259993.jpeg)\n
['Java']