Problem 1572

Abstract / Summary

Calculate the sum of both main diagonals of a square matrix and return the result.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1572.cpp

class Solution {
public:
    int diagonalSum(vector<vector<int>>& mat) {
        int sum = 0;
        for (int i = 0; i < mat.size(); i++)
        {
            sum += mat[i][i];
            auto j = mat.size() - i - 1;
            if (i != j)
                sum += mat[i][j];
        }
        return sum;
    }
};
14 lines | 331 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single public method diagonalSum. The method receives a square matrix represented as a vector of vectors of integers and returns the sum of the elements that lie on both the primary (top-left to bottom-right) and secondary (top-right to bottom-left) diagonals. The algorithm iterates once over the rows of the matrix, accumulating the required diagonal values while avoiding double-counting the central element when the matrix size is odd.

Key Steps

The core of the algorithm is a single for loop that traverses each row index i. Within each iteration two diagonal positions are identified: the element at column i for the primary diagonal and the element at column n-i-1 for the secondary diagonal, where n is the matrix dimension.

int sum = 0;
for (int i = 0; i < mat.size(); i++)
{
    sum += mat[i][i];
    auto j = mat.size() - i - 1;
    if (i != j)
        sum += mat[i][j];
}
return sum;
  • The statement sum += mat[i][i]; adds the primary diagonal element of the current row.
  • The variable j is computed as mat.size() - i - 1, which yields the column index for the secondary diagonal element in the same row.
  • The conditional if (i != j) ensures that when i and j refer to the same cell-occurring only for the middle element of an odd-sized matrix-the value is added only once.

Edge Cases Handled

The code gracefully handles matrices of size one. In that scenario mat.size() equals 1, the loop runs a single iteration with i = 0. Both diagonal indices resolve to 0, the condition i != j evaluates to false, and the single element is added exactly once, producing the correct sum.

For odd-dimensional matrices larger than one, the central element belongs to both diagonals. The conditional check if (i != j) prevents this element from being added twice, thereby preserving the mathematical definition of the diagonal sum.

Even-dimensional matrices do not have a shared central element, so the condition always evaluates to true for the secondary diagonal addition, and both diagonal contributions are included for every row.

The implementation also implicitly assumes that the input matrix is square. Because the loop bounds and index calculations rely on mat.size() for both row and column dimensions, any rectangular input would lead to out-of-range access, but within the intended contract of a square matrix the code operates safely.

Performance Considerations

The algorithm performs a single pass over the matrix rows, resulting in a linear number of iterations relative to the matrix dimension. Each iteration executes a constant amount of work: two array accesses, a simple arithmetic calculation for the secondary index, and a conditional check. This design eliminates the need for nested loops or auxiliary data structures, keeping the runtime overhead minimal.

By using the loop index i directly to compute both diagonal positions, the code avoids extra function calls or iterator objects, which contributes to cache-friendly access patterns. The conditional guard if (i != j) eliminates redundant addition without incurring significant branching cost because the branch is predictable: it is taken only for the middle row of odd-sized matrices.

Overall, the implementation achieves an efficient traversal with low memory footprint, relying solely on a few integer variables and the input matrix itself.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a flat square grid made of tiles, like a tiled floor in a playroom. This code is a little helper that walks along the two main paths that cross in the center of the grid, just like an X shape. It starts at the top left corner and moves down one step at a time, adding up the numbers it finds on the way. At the same time, it looks at the opposite corner and moves toward the other side. When it picks up the numbers, it makes sure to watch out for the very middle tile. If the rows cross over at a single tile in the center, it counts that tile only once so the final big number is exactly right. It just travels through those two lines across the square and gathers all the values together until it reaches the end.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.04 | σ = 0.59

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go C Rust TS
Progiez C++ Python Java
github AdelDaniel Dart
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
AdelDaniel Dart
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
35 links | 22 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality