Problem overview
The function diagonalSum receives grid, a square vector<vector<int>> with as many rows as columns, and returns the sum of the cells on its main diagonal, from the top-left corner to the bottom-right one. A cell is on the diagonal when its row number and column number are equal: (0, 0), (1, 1), (2, 2) and so on. Rows and columns are numbered from 0.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, and the sum is 15. For [[7]] the single cell is the whole diagonal, so the answer is 7. For [[-1, 2], [3, -4]] the diagonal cells are -1 and -4, and the sum is -5; the 2 and the 3 are not on the diagonal.
Approach: one index does both jobs
The obvious way to visit a grid is two nested loops. Here that would be wasteful. Only cells where the row and column are the same count, so a second loop would visit every cell just to skip most of them. A single index i is enough: grid[i][i] is the diagonal cell of row i. Running i from 0 to one less than the number of rows touches each diagonal cell once.
The number of diagonal cells equals the grid's size n, so the loop runs n times instead of n * n. On the 3 by 3 example, the loop reads grid[0][0], grid[1][1] and grid[2][2], which are 1, 5 and 9, and the total is 15.
Step by step
- Create
totalas anintset to 0. No diagonal cell has been added yet. - Loop with an index. Use an
intifrom 0 whilei < grid.size(): one turn per row. - Add the diagonal cell.
total += grid[i][i]picks rowiwith the first bracket and columniof that row with the second. - Return
totalafter the loop. By then, one cell per row has been added.
The solution in C++
class Solution {
public:
int diagonalSum(vector<vector<int>> &grid) {
int total = 0;
for (int i = 0; i < grid.size(); i++) {
total += grid[i][i];
}
return total;
}
};
C++ details:
- Why the grid must be square. The loop bound is
grid.size(), the number of rows, and the column index goes just as high. In a grid with fewer columns than rows,grid[i][i]would eventually read past the end of a row. The[]operator on a vector doesn't check bounds, so that would be undefined behaviour. The lesson guarantees a square grid. - Two brackets, two vectors.
grid[i]is avector<int>, the row, and the second[i]indexes that row. - Compound assignment.
total += xis shorthand fortotal = total + x. - Unsigned size.
grid.size()is unsigned whileiis anint. For small grids the comparison behaves, and a compiler may warn about the mix.
Complexity
The loop runs n times for an n by n grid, so the time is O(n), not O(n²), even though the grid holds n² cells. Space is constant: one counter and one total.
Edge cases and common mistakes
- One cell.
[[7]]gives 7. - Negative values.
[[-1, 2], [3, -4]]gives -5. - Off-diagonal values.
[[1, 2], [3, 4]]gives 5: the 2 and the 3 are ignored. - Nested loops with a condition. Looping over every cell and adding when
row == colgives the same answer, but it doesn²steps for work that needsn. - Mixing up the indices.
grid[i][0]sums the first column, not the diagonal.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives 15.[[7]]gives 7.[[-1, 2], [3, -4]]gives -5.[[1, 2], [3, 4]]gives 5.
