Start learning free

LESSON 258 OF 667 · NESTED LOOPS OVER GRIDS

Diagonal Sum in C++: One Loop over a Square Grid

Practice Read the full explanation

Given a square grid of integers grid, with as many rows as columns, return the sum of the cells on its diagonal: the cells that go from the top-left corner to the bottom-right corner.

A grid is a vector of rows, and each row is a vector of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right. A cell is on the diagonal when its row number and its column number are the same: row 0 and column 0, row 1 and column 1, and so on.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: 15
Explanation: The diagonal cells are 1, 5 and 9: 1 + 5 + 9 = 15.

Example 2:

Input: grid = [
  [7]
]
Output: 7
Explanation: A grid with one cell: that cell is the whole diagonal.

Example 3:

Input: grid = [
  [-1, 2],
  [3, -4]
]
Output: -5
Explanation: The diagonal cells are -1 and -4: -1 + (-4) = -5. The 2 and the 3 are not on the diagonal.

 

Constraints:

  • grid has n rows and n columns, with n at least 1.
  • Every value is an integer between -1000 and 1000; values can be negative.
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · NESTED LOOPS OVER GRIDS

    Diagonal Sum in C++, explained

    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

    1. Create total as an int set to 0. No diagonal cell has been added yet.
    2. Loop with an index. Use an int i from 0 while i < grid.size(): one turn per row.
    3. Add the diagonal cell. total += grid[i][i] picks row i with the first bracket and column i of that row with the second.
    4. Return total after 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 a vector<int>, the row, and the second [i] indexes that row.
    • Compound assignment. total += x is shorthand for total = total + x.
    • Unsigned size. grid.size() is unsigned while i is an int. 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 == col gives the same answer, but it does n² steps for work that needs n.
    • 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.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free