Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
!! BIG ANNOUNCEMENT !!\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies relat
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. I planned to give for next 10,000 Subscribers as well. If you\'re interested **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\n\n- We can iterate over each row of the matrix and add the diagonal elements to a result variable.\n- The first diagonal element is mat[i][i], and the second diagonal element is mat[i][n - i - 1].\n- If the matrix has an odd size, we need to subtract the center element from the result, as it will have been added twice.\n- Finally, we can return the result.\n\n# Intuition:\n\n- The diagonal elements in a matrix have a unique property, in that their row and column indices are equal or differ by a constant amount.\n- Specifically, for a square matrix, the diagonal elements have row and column indices of the form (i, i) or (i, n - i - 1).\n- Therefore, we can iterate over each row of the matrix, and add the diagonal elements to a running sum.\n- If the matrix has an odd size, the center element will be part of both diagonals and will be added twice. We can correct this by subtracting it once from the running sum.\n- Finally, we can return the sum as the answer.\n\n```Python []\nclass Solution:\n    def diagonalSum(self, mat: List[List[int]]) -> int:\n        n = len(mat)\n        result = 0\n        for i in range(n):\n            result += mat[i][i] + mat[i][n - i - 1]\n        if n % 2 == 1:\n            result -= mat[n // 2][n // 2]\n        return result\n\n```\n```Java []\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int n = mat.length;\n        int result = 0;\n        for (int i = 0; i < n; i++) {\n            result += mat[i][i] + mat[i][n - i - 1];\n        }\n        if (n % 2 == 1) {\n            result -= mat[n / 2][n / 2];\n        }\n        return result;\n    }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n    int diagonalSum(vector<vector<int>>& mat) {\n        int n = mat.size();\n        int result = 0;\n        for (int i = 0; i < n; i++) {\n            result += mat[i][i] + mat[i][n - i - 1];\n        }\n        if (n % 2 == 1) {\n            result -= mat[n / 2][n / 2];\n        }\n        return result;\n    }\n};\n\n```\n\n# An Upvote will be encouraging \uD83D\uDC4D\n
['Array', 'C++', 'Java', 'Python3']