Faster Than 100%🔥🔥C++🏆🏆java Code🏆🏆Step By Step Explanation
\n# Approach\n> First, we get the size of the input matrix mat using mat.size().\n\nint n = mat.size();\n\n> We then initialize the variable sum to zero.\n\nint
\n# Approach\n> First, we get the size of the input matrix mat using mat.size().\n```\nint n = mat.size();\n```\n> We then initialize the variable sum to zero.\n```\nint sum = 0;\n```\n> We use a for loop to iterate over each row of the matrix. For each row i, we add the value of the primary diagonal element mat[i][i] to the sum variable.\n```\nfor (int i = 0; i < n; i++) {\n    sum += mat[i][i]; \n```\n> check if the current element is not part of the primary diagonal (i.e., if it\'s not the central element). If it\'s not, we add the value of the secondary diagonal element mat[i][n - i - 1] to the sum variable.\n```\nif (i != n - i - 1) {\n    sum += mat[i][n - i - 1]; \n}\n```\n> return the sum variable.\n```\nreturn sum;\n```\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(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            // primary diagonal\n            sum += mat[i][i]; \n            // neglect the central element\n            if (i != n - i - 1) { \n                // secondary diagonal\n                sum += mat[i][n - i - 1]; \n            }\n        }\n        return sum;\n    }\n};\n\n```\n# java code\n```\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int n = mat.length; \n    int sum = 0; \n    for (int i = 0; i < n; i++) { \n        sum += mat[i][i]; \n        if (i != n - i - 1) { \n            sum += mat[i][n - i - 1]; \n        }\n    }\n    return sum; \n}\n```
['Array', 'C++', 'Java']