Leetcode 1572: Matrix Diagonal Sum

grid47
grid47
Exploring patterns and algorithms
Jun 2, 2024 5 min read

You are given a square matrix of integers. Your task is to calculate the sum of all the elements located on the primary diagonal and the secondary diagonal, excluding the element that appears on both diagonals (i.e., the center element in an odd-sized matrix).
Problem
Approach
Steps
Complexity
Input: The input consists of a square matrix, where each element is an integer. The matrix has equal number of rows and columns.
Example: Input: mat = [[3, 1, 2], [4, 5, 6], [7, 8, 9]]
Constraints:
• 1 <= n <= 100
• 1 <= mat[i][j] <= 100
Output: Return the sum of the elements on both the primary and secondary diagonals. If the matrix size is odd, subtract the center element once to avoid double-counting.
Example: Output: 25
Constraints:
Goal: To calculate the sum of the diagonal elements efficiently without counting the center element twice.
Steps:
• Iterate through the matrix and sum the elements on the primary diagonal (mat[i][i]) and secondary diagonal (mat[i][n-i-1]).
• If the matrix size is odd, subtract the center element (mat[n//2][n//2]) once as it's counted in both diagonals.
Goal: The matrix has dimensions n x n, where 1 <= n <= 100.
Steps:
• 1 <= mat.length <= 100
• 1 <= mat[i][j] <= 100
Assumptions:
• The matrix is square, meaning the number of rows is equal to the number of columns.
Input: Example 1: mat = [[3, 1, 2], [4, 5, 6], [7, 8, 9]]
Explanation: The diagonals sum: 3 + 5 + 9 + 2 + 7 = 25. No element is counted twice.

Input: Example 2: mat = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Explanation: The diagonals sum: 1 + 1 + 1 + 1 + 1 = 5. The center element is counted only once.

Input: Example 3: mat = [[5]]
Explanation: Only one element exists, and that is the center element. The sum is 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus