Sum the Two Diagonals Without Double Counting

Quick Overview

Sum the Two Diagonals Without Double Counting. For the square integer matrix mat, add every entry on either main diagonal. An entry lying on both diagonals contributes only once. Return the sum.

Sum the Two Diagonals Without Double Counting

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem For the square integer matrix `mat`, add every entry on either main diagonal. An entry lying on both diagonals contributes only once. Return the sum. ```cpp class Solution { public: int diagonalSum(vector<vector<int>>& mat); }; ``` ### Examples **Example 1:** ```text mat = [[2,4],[6,8]] Output: 20 Explanation: Every cell of a 2 by 2 matrix lies on a diagonal. ``` **Example 2:** ```text mat = [[2,1,3],[1,7,1],[5,1,4]] Output: 21 Explanation: The five distinct diagonal entries are 2, 3, 7, 5, and 4. ``` ### Constraints - `n == mat.length == mat[i].length`. - `1 <= n <= 100`. - Every cell is an integer from `1` through `100`. ### Clarifying Questions The matrix is square. The center exists as a shared diagonal entry only for odd `n`. ```hint Inspect the structure Which cells are entitled to contribute, including a cell that belongs to both diagonals? ``` ### Reasoning checkpoints - Identify the two diagonal columns per row. - Count the shared center once rather than twice. ### Optional extensions How would you sum the border and both diagonals while avoiding all overlaps?

Overview: Sum the Two Diagonals Without Double Counting. For the square integer matrix mat, add every entry on either main diagonal. An entry lying on both diagonals contributes only once. Return the sum.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

For the square integer matrix mat, add every entry on either main diagonal. An entry lying on both diagonals contributes only once. Return the sum.

class Solution {
public:
    int diagonalSum(vector<vector<int>>& mat);
};

Examples

Example 1:

mat = [[2,4],[6,8]]
Output: 20
Explanation: Every cell of a 2 by 2 matrix lies on a diagonal.

Example 2:

mat = [[2,1,3],[1,7,1],[5,1,4]]
Output: 21
Explanation: The five distinct diagonal entries are 2, 3, 7, 5, and 4.

Constraints

  • n == mat.length == mat[i].length .
  • 1 <= n <= 100 .
  • Every cell is an integer from 1 through 100 .

Clarifying Questions Guidance

The matrix is square. The center exists as a shared diagonal entry only for odd n.

Reasoning checkpoints

  • Identify the two diagonal columns per row.
  • Count the shared center once rather than twice.

Optional extensions

How would you sum the border and both diagonals while avoiding all overlaps?