Java Optimized Solution || O(n) Time Complexity || Beats 100% || Runtime 0ms || Short & Simple
\n\n# Approach: \nCalculating sum of primary diagonal elements i.e elements who satisfy the condition : i=j . For the secondary diagonal elements, condition is:
\n\n# Approach: \nCalculating sum of primary diagonal elements i.e elements who satisfy the condition : i=j . For the secondary diagonal elements, condition is:  i+j= n-1 , which implies, j= n-i-1 , So we further calculate the sum of secondary diagonal elements ( i, n-i-1) by checking for the case where a primary diagonal element exists which is also a secondary diagonal element thereby excluding it to be added twice in our sum. \n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n\nHope this helps!!\nDo Upvote if you like it.\n\nThanks :)\n\n# Code\n```\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int sum=0;\n        for(int i=0; i<mat.length; i++){\n            sum+= mat[i][i]; //sum of primary diagonal elements (where i=j)\n            // Checking for primary diagonal element which is also a secondary diagonal element\n            if(i!= mat.length-i-1){\n                sum+= mat[i][mat.length-i-1]; //sum of secondary diagonal elements (where i+j=n-1)\n            }    \n        }\n        return sum;    \n    }\n}\n        \n```
['Java']