🧠
Brute Force (Nested Loops)
💡 This approach uses straightforward nested loops to check every element and add it if it lies on either diagonal. It helps beginners understand matrix indexing and diagonal conditions.
Intuition
Traverse every element in the matrix and check if it belongs to the primary or secondary diagonal. Sum those elements, taking care to avoid double counting the center element.
Algorithm
- Initialize sum to 0.
- Iterate over each row i from 0 to n-1.
- Within each row, iterate over each column j from 0 to n-1.
- If i == j (primary diagonal) or i + j == n - 1 (secondary diagonal), add mat[i][j] to sum.
- If n is odd, subtract the center element once to avoid double counting.
- Return the final sum.
💡 The nested loops make it easy to understand which elements belong to diagonals but are inefficient for large matrices.
def diagonalSum(mat):
n = len(mat)
total = 0
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1:
total += mat[i][j]
if n % 2 == 1:
total -= mat[n//2][n//2]
return total
# Driver code
if __name__ == '__main__':
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(diagonalSum(matrix)) # Output: 25
Line Notes
n = len(mat)Determine the size of the square matrix to control loops.
for i in range(n)Outer loop iterates over each row index.
for j in range(n)Inner loop iterates over each column index.
if i == j or i + j == n - 1Check if current element lies on primary or secondary diagonal.
total += mat[i][j]Add diagonal element to running total.
if n % 2 == 1Check if matrix size is odd to handle center element double counting.
total -= mat[n//2][n//2]Subtract center element once to avoid counting it twice.
return totalReturn the computed sum of diagonals.
public class Solution {
public static int diagonalSum(int[][] mat) {
int n = mat.length;
int total = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || i + j == n - 1) {
total += mat[i][j];
}
}
}
if (n % 2 == 1) {
total -= mat[n / 2][n / 2];
}
return total;
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(diagonalSum(matrix)); // Output: 25
}
}
Line Notes
int n = mat.length;Get matrix dimension for loop bounds.
for (int i = 0; i < n; i++)Loop over rows.
for (int j = 0; j < n; j++)Loop over columns.
if (i == j || i + j == n - 1)Identify diagonal elements by indices.
total += mat[i][j];Accumulate diagonal element values.
if (n % 2 == 1)Check for odd dimension to handle center overlap.
total -= mat[n / 2][n / 2];Remove double counted center element.
return total;Return final diagonal sum.
#include <iostream>
#include <vector>
using namespace std;
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size();
int total = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || i + j == n - 1) {
total += mat[i][j];
}
}
}
if (n % 2 == 1) {
total -= mat[n/2][n/2];
}
return total;
}
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
cout << diagonalSum(matrix) << endl; // Output: 25
return 0;
}
Line Notes
int n = mat.size();Determine matrix size for iteration limits.
for (int i = 0; i < n; i++)Iterate over rows.
for (int j = 0; j < n; j++)Iterate over columns.
if (i == j || i + j == n - 1)Check if element is on either diagonal.
total += mat[i][j];Add diagonal element to total sum.
if (n % 2 == 1)Detect odd dimension to adjust for center element.
total -= mat[n/2][n/2];Subtract center element once to avoid double counting.
return total;Return the computed diagonal sum.
function diagonalSum(mat) {
const n = mat.length;
let total = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i === j || i + j === n - 1) {
total += mat[i][j];
}
}
}
if (n % 2 === 1) {
total -= mat[Math.floor(n/2)][Math.floor(n/2)];
}
return total;
}
// Test
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(diagonalSum(matrix)); // Output: 25
Line Notes
const n = mat.length;Get matrix size for loops.
for (let i = 0; i < n; i++)Loop over rows.
for (let j = 0; j < n; j++)Loop over columns.
if (i === j || i + j === n - 1)Check if element is on primary or secondary diagonal.
total += mat[i][j];Add diagonal element to total sum.
if (n % 2 === 1)Check for odd dimension to handle center overlap.
total -= mat[Math.floor(n/2)][Math.floor(n/2)];Subtract center element once to avoid double counting.
return total;Return the final sum.
We visit every element in the n x n matrix once, so time is O(n^2). We use only a few variables, so space is O(1).
💡 For n=10, this means 100 operations, which is manageable but inefficient for very large matrices.
Interview Verdict: Accepted
This approach works correctly but is not optimal for large matrices due to unnecessary checks.