DevPath

← All problems

Diagonal Sum

Easy matrix

Description

Return the sum of both diagonals of a square matrix, counting the shared centre only once.

Constraints

1 <= n <= 100

Examples

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: 25

Hints (1)
  • Sum the main diagonal, then the anti-diagonal, avoiding double-counting the centre.

Solutions

Sum both diagonals. · Time O(n) · Space O(1)

func diagonalSum(matrix [][]int) int {
    n := len(matrix)
    sum := 0
    for i := 0; i < n; i++ {
        sum += matrix[i][i]
        if i != n-1-i {
            sum += matrix[i][n-1-i]
        }
    }
    return sum
}

Create a free account to submit solutions, track progress and save problems.

Create account