Super easy | Beginner Friendly | 100% efficient code
Intuition\nThe first thought is to iterate through the matrix and sum up the elements of the primary and secondary diagonals. For the primary diagonal, we add t
# Intuition\nThe first thought is to iterate through the matrix and sum up the elements of the primary and secondary diagonals. For the primary diagonal, we add the elements where the row index equals the column index. For the secondary diagonal, we add the elements where the row index and the column index sum up to the size of the matrix minus one. We need to be careful not to double-count the center element in matrices of odd size.\n\n# Approach\n1. Initialize a variable `sum` to zero to store the sum of the diagonal elements.\n2. Loop through each row `i` of the matrix:\n   - Add the element at the primary diagonal position `mat[i][i]` to `sum`.\n   - If `i` is not equal to `mat.length - 1 - i` (to avoid double-counting the central element in odd-sized matrices), add the element at the secondary diagonal position `mat[i][mat.length - 1 - i]` to `sum`.\n3. Return the `sum` after iterating through all the rows.\n\n# Complexity\n- **Time complexity:** \\( O(n) \\), where \\( n \\) is the number of rows (or columns) in the matrix. This is because we loop through the matrix only once.\n- **Space complexity:** \\( O(1) \\), as we are using a constant amount of extra space.\n\n# Code\n```java\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int sum = 0;\n        for (int i = 0; i < mat.length; i++) {\n            // Add the primary diagonal element\n            sum += mat[i][i];\n\n            // Add the secondary diagonal element if it\'s not the same as the primary diagonal element\n            if (i != mat.length - 1 - i) {\n                sum += mat[i][mat.length - 1 - i];\n            }\n        }\n        return sum;\n    }\n}\n```\n
['Java']