Easy Solution in JAVA
Approach\n Describe your approach to solving the problem. \nThe given code represents a class named Solution with a method diagonalSum that calculates the sum o
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given code represents a class named `Solution` with a method `diagonalSum` that calculates the sum of the elements along the diagonals of a square matrix. Here\'s an explanation of the approach:\n\n1. Initialize a variable `sum` to 0 to store the cumulative sum of the diagonal elements.\n2. Get the length of the input matrix `mat` and store it in the variable `m`. Since `mat` is a square matrix, the length of any row or column would be the same.\n3. Iterate over the rows of the matrix using a for loop with the variable `i` ranging from 0 to `m-1`.\n4. For each row `i`, add the element `mat[i][i]` to `sum`. This represents the element on the main diagonal.\n5. Additionally, add the element `mat[i][m-i-1]` to `sum`. This represents the element on the secondary diagonal.\n6. After the loop, check if the length of the matrix `m` is odd (i.e., `m % 2 != 0`).\n7. If `m` is odd, subtract the element `mat[m/2][m/2]` from `sum`. This element is located at the intersection of the main and secondary diagonals and gets added twice in the previous steps, so it needs to be subtracted once.\n8. Finally, return the calculated sum.\n\nThe overall approach is to iterate over the matrix, adding the elements on the main and secondary diagonals to the sum. If the matrix size is odd, we subtract the intersection element to avoid double counting.\n\n# Complexity\n- Time complexity:\nThe time complexity of the given code is O(n), where n represents the size of the input matrix (assuming it is a square matrix with equal dimensions).\n\n- Space complexity:\nThe space complexity of the code is O(1) because it uses a constant amount of additional space to store the sum and the variable m. The space usage does not depend on the size of the input matrix, making it constant or O(1).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int diagonalSum(int[][] mat) {\n        int sum =0;\n        int m=mat.length;\n        for(int i=0;i<m;i++){\n            sum += mat[i][i] + mat[i][m-i-1];\n        }\n        if(m % 2 != 0) \n            sum -= mat[m/2][m/2];\n        return sum;\n        }\n}\n\n```
['Java']