Start learning free

LESSON 258 OF 285 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Java: One Loop over grid[i][i]

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 an array of rows, and each row is an array 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

    JAVA · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Java, explained

    Problem overview

    Given a square grid grid of type int[][], with as many rows as columns, diagonalSum returns the sum of the cells on the diagonal that runs from the top-left corner to the bottom-right one. A cell is on the diagonal when its row number and column number are the same: row 0 and column 0, row 1 and column 1, and so on. Rows and columns are counted from 0.

    For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, so the answer is 15. For [[7]] the single cell is the whole diagonal, and the answer is 7. For [[-1, 2], [3, -4]] the diagonal cells are -1 and -4, so the answer is -5; the 2 and the 3 are not on the diagonal.

    Approach

    Summing a grid usually takes two loops, one over rows and one over columns. Here that would be wasteful: a nested pair of loops would visit every cell only to skip most of them. The diagonal has a simple rule, though: the row number equals the column number. So one index i is enough to name each diagonal cell, as grid[i][i].

    The loop runs i from 0 up to the number of rows, and each turn adds one diagonal cell. A grid with n rows has exactly n diagonal cells, so the loop runs n times.

    Step by step

    1. Create an int named total starting at 0. No diagonal cell has been added yet.
    2. Write a for loop with an int i from 0 while i < grid.length. That is one turn per row, and since the grid is square, one turn per column too.
    3. Inside the loop, add grid[i][i] to total with +=. The first [i] picks row i, and the second picks column i in that row.
    4. After the loop, return total. By then every diagonal cell has been added, one per row.

    Tracing the first example

    For the 3 by 3 grid with 1 to 9, the loop reads grid[0][0], which is 1, then grid[1][1], which is 5, then grid[2][2], which is 9. The total goes 1, 6, 15, and the method returns 15.

    The solution in Java

    class Solution {
        public int diagonalSum(int[][] grid) {
            int total = 0;
            for (int i = 0; i < grid.length; i++) {
                total += grid[i][i];
            }
            return total;
        }
    }
    

    Java details in this code:

    • An index loop, not for-each. The for-each form gives values without their positions. The diagonal depends on positions, so the loop needs the index i.
    • grid[i][i] is two lookups. grid[i] is the row, an int[], and the second [i] indexes into it.
    • grid.length counts rows. It is a field with no parentheses. For a square grid, it is also the column count, which is why one bound is enough.
    • Bad indexes throw. If the grid were not square, an index could run past a row's end. The lesson guarantees a square grid, so it doesn't happen here.

    Complexity

    The loop runs once per row, doing one addition each time, so the time is O(n) for an n by n grid. It doesn't depend on the n * n cells, because the other cells are never read. The extra space is O(1): one variable for the total and one for the index.

    Edge cases and common mistakes

    • A one-cell grid. [[7]] has grid.length equal to 1, so the loop runs once and the method returns 7.
    • Negative values. They lower the total. For [[-1, 2], [3, -4]], the sum is -1 plus -4, which is -5.
    • Nested loops with a check. Writing two loops and adding a cell only when row == col gives the same answer, but it reads n * n cells where n are needed.
    • Counting the middle twice. This task asks only for the main diagonal, from the top left to the bottom right. The other diagonal has the cells grid[i][n - 1 - i], and a task that adds both would need to count the center cell of an odd-sized grid once.
    • A wider grid. The lesson promises a square grid. If you passed [[1, 2, 3], [4, 5, 6]], which has two rows and three columns, the loop would add 1 and 5 and return 6, which is not a diagonal sum in the lesson's sense.

    Testing

    • diagonalSum(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) returns 15.
    • diagonalSum(new int[][]{{7}}) returns 7.
    • diagonalSum(new int[][]{{-1, 2}, {3, -4}}) returns -5.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free