C++ || Easy || Single Traversal Approach
Intuition\nInstead of traversing each element of a matrix by a nested loop to access the diagonal elements, we can optimize it to single traversal only.\n\n# Ap
# Intuition\nInstead of traversing each element of a matrix by a nested loop to access the diagonal elements, we can optimize it to single traversal only.\n\n# Approach\nHow we can access the diagonal elements: \n1. For principal diagonal elements (Diagonal elements which start from index 0,0), we can access it when both i and j index are equal i.e., i = j.\n2. To access elements that start from an index (0, length of row \u2013 1), we can access it when i+j = n-1 or j = n-1-i. \n\nSo, in single traversal, we can access the diagonal elements using index mat[i][i] (to traverse the principal diagonal element), and mat[i][n-i-1] (to traverse another diagonal element), then we initialize a count = 0, and add all those elements to count.\n\nIf the matrix is odd (i.e., the row and column are odd) then the middle element of the matrix will get counted twice, so after traversing the element we need to subtract the middle element.\n\n# Complexity\n- Time complexity: O(size of row or column of matrix)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n    int diagonalSum(vector<vector<int>>& mat) {\n        int count = 0;\n        int n = mat.size();\n        for(int i=0;i<n;i++)\n        {\n            count += mat[i][i];\n            count += mat[i][n-i-1];\n        }\n        if(mat.size()%2)\n        return count-mat[n/2][n/2];\n\n        return count;\n    }\n};\n```
['Array', 'Matrix', 'C++']