# The Diagonal Accountant

> Two diagonals cross in the center of every square.

Canonical URL: <https://datadriven.io/problems/the_diagonal_accountant>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given an n x n matrix, return the sum of main-diagonal and anti-diagonal values. For odd n, do NOT double-count the center element.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **matrix traversal with index arithmetic**, specifically accessing diagonal elements. It probes whether a candidate can derive the index patterns for main and anti-diagonals and handle the overlap at the center of odd-sized matrices.

---

### Break down the requirements

#### Step 1: Sum the main diagonal

Elements at positions `(i, i)` for i from 0 to n-1.

#### Step 2: Sum the anti-diagonal

Elements at positions `(i, n-1-i)` for i from 0 to n-1.

#### Step 3: Subtract the center if n is odd

When n is odd, position `(n//2, n//2)` is on both diagonals and gets counted twice.

---

### The solution

**Index-based diagonal traversal**

```python
def diagonal_sum(matrix: list) -> int:
    n = len(matrix)
    total = 0
    for i in range(n):
        total += matrix[i][i]
        total += matrix[i][n - 1 - i]
    if n % 2 == 1:
        total -= matrix[n // 2][n // 2]
    return total
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the side length. Only 2n elements are accessed.
> 
> **Space:** O(1). No extra data structures.

> **Interviewers Watch For**
>
> Whether you handle the center overlap correctly. Forgetting to subtract it is the most common bug.

> **Common Pitfall**
>
> Iterating the entire matrix (O(n^2)) when only 2n elements are needed. Strong candidates recognize this immediately.

---

## Common follow-up questions

- What if the matrix is not square? _(Tests that diagonals are only defined for square matrices; a rectangular matrix needs a different definition.)_
- How would you sum all diagonals (not just main and anti)? _(Tests iterating with row-column offset patterns.)_
- What if the matrix is stored as a 1D array? _(Tests converting 2D indices to 1D: `matrix[i * n + j]`.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_diagonal_accountant)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.