Optimized Single-Pass Solution with Explanation and clean code
\n\n# Approach\nThe solution calculates the sum of the main diagonal and the secondary diagonal of a square matrix, and returns the result. It iterates through 
\n\n# Approach\nThe solution calculates the sum of the main diagonal and the secondary diagonal of a square matrix, and returns the result. It iterates through the rows of the matrix and adds the elements from the main diagonal (i.e., mat[i][i]) and the secondary diagonal (i.e., mat[i][n-i-1]) to the sum variable. If the size of the matrix is odd, it subtracts the center element from the sum. Finally, the function returns the calculated sum.\n\nIn summary, this solution uses a single loop to iterate through the matrix, adds the diagonal elements to the sum, and then subtracts the center element (if the matrix size is odd) to obtain the final result. \n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n    int diagonalSum(vector<vector<int>>& mat) {\n        int n = mat.size();\n        int sum = 0;\n        for (int i = 0; i < n; i++) {\n            sum += mat[i][i]; // add element from main diagonal\n            sum += mat[i][n-i-1]; // add element from secondary diagonal\n            if (n % 2 == 1 && i == n / 2) { // subtract center element if matrix size is odd\n                sum -= mat[i][i];\n            }\n        }\n        return sum;\n    }\n};\n\n```
['Array', 'Matrix', 'C++', 'Java']