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;
}
};
Difficulty
and has an acceptance rate of about 84% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
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.
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
jis computed asmat.size() - i - 1, which yields the column index for the secondary diagonal element in the same row. - The conditional
if (i != j)ensures that wheniandjrefer 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 2133: Check if Every Row and Column Contains All Numbers
- problem 2319: Check if Matrix Is X-Matrix
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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