Bird
Raised Fist0
Interview PrepmatriceseasyAmazonGoogle

Matrix Diagonal Sum

Choose your preparation mode4 modes available
🎯
Matrix Diagonal Sum
easyMATRIXAmazonGoogle

Imagine you have a square photo grid and want to quickly find the sum of pixels along both diagonals to analyze brightness patterns.

💡 This problem is about traversing a square matrix to sum elements on its two diagonals. Beginners often struggle with avoiding double counting the center element when the matrix size is odd.
📋
Problem Statement

Given a square matrix mat of size n x n, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

1 ≤ n ≤ 10^3mat.length == nmat[i].length == n1 ≤ mat[i][j] ≤ 100
💡
Example
Input"[[1,2,3],[4,5,6],[7,8,9]]"
Output25

Primary diagonal sum = 1 + 5 + 9 = 15; Secondary diagonal sum = 3 + 5 + 7 = 15; Center element 5 counted twice, so subtract once: 15 + 15 - 5 = 25.

  • 1x1 matrix → sum is the single element
  • 2x2 matrix → no center overlap, sum all four diagonal elements
  • Odd-sized matrix → center element counted twice, must subtract once
  • Large matrix with max values → ensure no integer overflow
⚠️
Common Mistakes
Double counting the center element in odd-sized matrices

Output sum is larger than expected

✅ Subtract the center element once after summing both diagonals

Using nested loops unnecessarily

Slower code and more complex logic

✅ Use a single loop leveraging diagonal index properties

Incorrect index calculation for secondary diagonal

Wrong elements summed, incorrect result

✅ Use i + j == n - 1 or j = n - 1 - i for secondary diagonal

Not handling 1x1 matrix edge case

May cause errors or incorrect subtraction

✅ Check matrix size and handle center subtraction only if n > 1

🧠
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

  1. Initialize sum to 0.
  2. Iterate over each row i from 0 to n-1.
  3. Within each row, iterate over each column j from 0 to n-1.
  4. If i == j (primary diagonal) or i + j == n - 1 (secondary diagonal), add mat[i][j] to sum.
  5. If n is odd, subtract the center element once to avoid double counting.
  6. Return the final sum.
💡 The nested loops make it easy to understand which elements belong to diagonals but are inefficient for large matrices.
</>
Code
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.
⏱
Complexity
TimeO(n^2)
SpaceO(1)

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.

🧠
Better Approach (Single Loop with Direct Indexing)
💡 This approach leverages the properties of diagonals to sum elements in a single loop, improving efficiency and clarity.

Intuition

Since the primary diagonal elements have indices (i, i) and the secondary diagonal elements have indices (i, n-1-i), we can sum these directly in one pass.

Algorithm

  1. Initialize sum to 0.
  2. Iterate i from 0 to n-1.
  3. Add mat[i][i] (primary diagonal element) to sum.
  4. Add mat[i][n-1-i] (secondary diagonal element) to sum.
  5. If n is odd, subtract the center element once to avoid double counting.
  6. Return the sum.
💡 This approach reduces complexity by avoiding nested loops and directly accessing diagonal elements.
</>
Code
def diagonalSum(mat):
    n = len(mat)
    total = 0
    for i in range(n):
        total += mat[i][i] + mat[i][n - 1 - i]
    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)Get matrix size for loop control.
for i in range(n)Single loop to traverse diagonal indices.
total += mat[i][i] + mat[i][n - 1 - i]Add both primary and secondary diagonal elements in one step.
if n % 2 == 1Check for odd dimension to handle center overlap.
total -= mat[n//2][n//2]Subtract center element once to avoid double counting.
return totalReturn the computed sum.
public class Solution {
    public static int diagonalSum(int[][] mat) {
        int n = mat.length;
        int total = 0;
        for (int i = 0; i < n; i++) {
            total += mat[i][i] + mat[i][n - 1 - i];
        }
        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 size for iteration.
for (int i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add primary and secondary diagonal elements directly.
if (n % 2 == 1)Check for odd dimension to handle center overlap.
total -= mat[n / 2][n / 2];Subtract center element once to avoid double counting.
return total;Return the final 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++) {
        total += mat[i][i] + mat[i][n - 1 - i];
    }
    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 loop.
for (int i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add both diagonal elements in one step.
if (n % 2 == 1)Check for odd dimension to handle center overlap.
total -= mat[n/2][n/2];Subtract center element once to avoid double counting.
return total;Return the computed sum.
function diagonalSum(mat) {
    const n = mat.length;
    let total = 0;
    for (let i = 0; i < n; i++) {
        total += mat[i][i] + mat[i][n - 1 - i];
    }
    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 loop control.
for (let i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add primary and secondary diagonal elements directly.
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.
⏱
Complexity
TimeO(n)
SpaceO(1)

We only iterate once over n elements, accessing two diagonal elements per iteration, so time is O(n). Space remains constant.

💡 For n=10, this means 10 iterations and 20 element accesses, much faster than nested loops.
Interview Verdict: Accepted

This approach is optimal for this problem and preferred in interviews for clarity and efficiency.

🧠
Optimal Approach (In-Place Summation Without Extra Variables)
💡 This approach is a slight variation that emphasizes minimal variable usage and direct summation, useful for memory-constrained environments.

Intuition

Sum the diagonals directly during a single loop without storing intermediate sums in multiple variables, subtracting the center element if needed.

Algorithm

  1. Initialize a single variable total to 0.
  2. Loop i from 0 to n-1.
  3. Add mat[i][i] and mat[i][n-1-i] to total.
  4. If n is odd, subtract the center element once.
  5. Return total.
💡 This approach is essentially the same as the better approach but highlights minimalism and clarity.
</>
Code
def diagonalSum(mat):
    total = 0
    n = len(mat)
    for i in range(n):
        total += mat[i][i] + mat[i][n - 1 - i]
    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
total = 0Initialize sum accumulator.
n = len(mat)Get matrix size for loop.
for i in range(n)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i]Add both diagonal elements per iteration.
if n % 2 == 1Check for odd dimension to handle center overlap.
total -= mat[n//2][n//2]Subtract center element once to avoid double counting.
return totalReturn the final sum.
public class Solution {
    public static int diagonalSum(int[][] mat) {
        int total = 0;
        int n = mat.length;
        for (int i = 0; i < n; i++) {
            total += mat[i][i] + mat[i][n - 1 - i];
        }
        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 total = 0;Initialize sum accumulator.
int n = mat.length;Get matrix size.
for (int i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add diagonal elements directly.
if (n % 2 == 1)Check for odd dimension.
total -= mat[n / 2][n / 2];Subtract center element once.
return total;Return the sum.
#include <iostream>
#include <vector>
using namespace std;

int diagonalSum(vector<vector<int>>& mat) {
    int total = 0;
    int n = mat.size();
    for (int i = 0; i < n; i++) {
        total += mat[i][i] + mat[i][n - 1 - i];
    }
    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 total = 0;Initialize sum accumulator.
int n = mat.size();Get matrix size.
for (int i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add diagonal elements directly.
if (n % 2 == 1)Check for odd dimension.
total -= mat[n/2][n/2];Subtract center element once.
return total;Return the sum.
function diagonalSum(mat) {
    let total = 0;
    const n = mat.length;
    for (let i = 0; i < n; i++) {
        total += mat[i][i] + mat[i][n - 1 - i];
    }
    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
let total = 0;Initialize sum accumulator.
const n = mat.length;Get matrix size.
for (let i = 0; i < n; i++)Single loop over indices.
total += mat[i][i] + mat[i][n - 1 - i];Add diagonal elements directly.
if (n % 2 === 1)Check for odd dimension.
total -= mat[Math.floor(n/2)][Math.floor(n/2)];Subtract center element once.
return total;Return the sum.
⏱
Complexity
TimeO(n)
SpaceO(1)

Single pass over n elements, constant space usage.

💡 This is the most efficient approach for this problem size.
Interview Verdict: Accepted

This is the preferred approach in interviews due to simplicity and optimal performance.

📊
All Approaches - One-Glance Tradeoffs
💡 The single loop approach is best for interviews due to clarity and efficiency; brute force is useful for initial understanding.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute Force (Nested Loops)O(n^2)O(1)NoN/AMention only - never code
2. Better Approach (Single Loop with Direct Indexing)O(n)O(1)NoN/ACode this approach
3. Optimal Approach (In-Place Summation Without Extra Variables)O(n)O(1)NoN/ACode this approach for minimalism
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice coding all approaches, and prepare to explain tradeoffs clearly in interviews.

How to Present

Step 1: Clarify the problem and constraints with the interviewer.Step 2: Describe the brute force approach using nested loops.Step 3: Optimize to a single loop using diagonal index properties.Step 4: Code the optimal solution clearly and test with examples.Step 5: Discuss edge cases and possible follow-ups.

Time Allocation

Clarify: 2min → Approach: 3min → Code: 5min → Test: 3min. Total ~13min

What the Interviewer Tests

Interviewer tests your understanding of matrix indexing, handling of overlapping center element, and ability to optimize nested loops to single pass.

Common Follow-ups

  • What if the matrix is not square? → Diagonal sums are undefined or need clarification.
  • Can you do this in-place without extra space? → Yes, as shown, only variables used.
  • How to handle very large matrices? → Use single loop approach for efficiency.
  • What if you want to return the sum of only one diagonal? → Adjust loop accordingly.
💡 These follow-ups test your ability to adapt the solution to variations and constraints.
🔍
Pattern Recognition

When to Use

1) Problem involves square matrix; 2) Need sum of elements on diagonals; 3) Avoid double counting center element; 4) Efficient traversal required.

Signature Phrases

sum of matrix diagonalsprimary and secondary diagonal elementsavoid counting center element twice

NOT This Pattern When

Problems involving only row or column sums, or non-square matrices without diagonal focus.

Similar Problems

Diagonal Traverse - similar diagonal traversal patternSpiral Matrix - matrix traversal with different pattern

Practice

(1/5)
1. The following code attempts to count negative numbers in a sorted matrix using the staircase search approach. Identify the line containing the subtle bug that can cause incorrect results or infinite loops.
def countNegatives(grid):
    m, n = len(grid), len(grid[0])
    count = 0
    row, col = 0, n - 1
    while row < m and col >= 0:
        if grid[row][col] < 0:
            count += m - row
            row += 1  # Bug here
        else:
            col -= 1
    return count
medium
A. Line where row is incremented after finding a negative
B. Line where row and col are initialized
C. Line where col is decremented after finding a non-negative
D. Line where count is incremented by m - row

Solution

  1. Step 1: Understand staircase logic

    When a negative is found, we move left (col--) to check smaller elements in the same row.
  2. Step 2: Identify incorrect movement

    Incrementing row after finding a negative skips checking left elements, causing missed negatives or infinite loops.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct move on negative is col--, not row++ [OK]
Hint: On negative, move left; on non-negative, move down [OK]
Common Mistakes:
  • Swapping row and col increments
  • Miscounting negatives by skipping columns
  • Infinite loops due to wrong pointer moves
2. Identify the bug in the following in-place Game of Life code snippet that causes incorrect neighbor counts and final states.
medium
A. Line checking neighbors lacks boundary condition checks causing index errors
B. Final loop does not convert encoded states back to original states
C. Neighbor counting incorrectly includes dead cells as live
D. Encoding uses wrong integers for state transitions

Solution

  1. Step 1: Examine neighbor counting loop

    The code checks board[x][y] without verifying if x,y are within valid indices, risking index errors or invalid counts.
  2. Step 2: Confirm other parts are correct

    Final decoding loop correctly converts 2->0 and 3->1; encoding uses correct integers; neighbor counting excludes dead cells properly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing boundary check causes incorrect neighbor counts or runtime errors [OK]
Hint: Always check boundaries before accessing neighbors [OK]
Common Mistakes:
  • Forgetting boundary checks in neighbor loops
  • Not finalizing encoded states after first pass
  • Misusing encoding integers
3. What is the space complexity of the optimal in-place layer-by-layer rotation algorithm for an n x n matrix, and why might some candidates mistakenly think it is higher?
medium
A. O(n^2) because the entire matrix is modified in place.
B. O(log n) because the algorithm processes layers recursively.
C. O(n) due to the recursion stack or auxiliary arrays used during rotation.
D. O(1) because only a fixed number of variables are used regardless of matrix size.

Solution

  1. Step 1: Identify space usage

    The algorithm uses only a few variables (indices, temp storage) regardless of matrix size.
  2. Step 2: Understand common misconceptions

    Some think space is O(n) or more due to confusion with extra matrix or recursion, but no extra arrays or recursion are used.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Only constant extra variables used, so space is O(1) [OK]
Hint: In-place means constant extra space regardless of input size [OK]
Common Mistakes:
  • Confusing time complexity with space
  • Assuming recursion or extra arrays are used
4. Suppose the matrix can contain duplicate values and you want to find all lucky numbers (minimum in their row and maximum in their column). Which modification to the optimal approach correctly handles duplicates without missing any lucky numbers?
hard
A. After precomputing row minimums and column maximums, return only the first element matching both conditions per row to avoid duplicates.
B. Use sets to store all minimum values per row and maximum values per column, then find all elements that appear in both sets.
C. Modify the single pass to check if the element equals the row minimum and column maximum, allowing multiple lucky numbers per row or column.
D. Sort each row and column and pick the intersection of minimums and maximums to find lucky numbers.

Solution

  1. Step 1: Understand duplicates impact

    Duplicates mean multiple elements in a row can be minimum and multiple in a column can be maximum.
  2. Step 2: Modify single pass check

    Instead of returning only one per row, check each element if it equals the row minimum and column maximum, allowing multiple lucky numbers.
  3. Step 3: Avoid unnecessary data structures

    Using sets (B) or sorting (D) adds overhead and complexity without benefit. Returning only first match (A) misses valid lucky numbers.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Check all elements against precomputed mins and maxs -> handles duplicates [OK]
Hint: Check all elements, not just first per row [OK]
Common Mistakes:
  • Returning only first match per row
  • Using extra data structures unnecessarily
  • Sorting instead of direct checks
5. Suppose the problem is modified so that the matrix is rectangular (not necessarily square). Which of the following statements about adapting the in-place rotation algorithm is true?
hard
A. The layer-by-layer four-way swap algorithm works unchanged for rectangular matrices.
B. In-place rotation is impossible for non-square matrices; extra space or a different approach is required.
C. Transposing and reversing rows can rotate rectangular matrices in-place without issues.
D. Rotating rectangular matrices by 90 degrees clockwise can be done by swapping elements only in the first row.

Solution

  1. Step 1: Understand matrix shape constraints

    In-place rotation by 90 degrees requires the matrix to be square because dimensions swap (rows become columns).
  2. Step 2: Evaluate options

    Layer-by-layer swaps rely on equal row and column counts; rectangular matrices require extra space or new matrix to hold rotated result.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Non-square matrices cannot be rotated in-place without dimension mismatch [OK]
Hint: In-place 90° rotation requires square matrix due to dimension swap [OK]
Common Mistakes:
  • Assuming in-place rotation works for rectangular matrices
  • Confusing transpose with rotation for non-square matrices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard