0% completed
Problem 2: Matrix Diagonal Sum (easy)
Problem Statement
Given a square matrix (2D array), calculate the sum of its two diagonals.
The two diagonals in consideration are the primary diagonal that spans from the top-left to the bottom-right and the secondary diagonal that spans from top-right to bottom-left. If a number is part of both diagonals (which occurs only for odd-sized matrices), it should be counted only once in the sum.
Examples
- Example 1:
- Input:
[[1,2,3], [4,5,6], [7,8,9]] - Expected Output: 25
- Input:
.....
.....
.....
Fabrice L
· 2 years ago
You don't need to iterate over the entire array, you can just get half of it and retrieve values from the 4 "corners", and then add the middle point in case of a odd number of rows.
class Solution { diagonalSum(mat) { let totalSum = 0; // Initialize the total sum const len = mat.length; for (let i = 0; i < Math.floor(len / 2); i += 1) { totalSum += ( mat[i][i] + mat[i][len - 1 - i] + mat[len - 1 - i][i] + mat[len - 1 - i][len - 1 - i] ); } if (len % 2 === 1) { // add center let pt = Math.floor(len / 2); totalSum += mat[pt][pt]; } return totalSum; // Return the calculated total sum } }
Naman Jindal
· 2 years ago
diagonalSum(mat) { let totalSum = 0; // Initialize the total sum let n = mat.length; // ToDo: Write Your Code Here.//[[5]] for(let i = 0; i < n ; i++){ if(i !== n-i-1){ totalSum+=(mat[i][i] + mat[i][n-1-i]) }else{ totalSum+=mat[i][i] } } return totalSum; // Return the calculated total sum }
Andrew Sologor
· a year ago
func diagonalSum(mat [][]int) int { totalSum := 0 i := 0 j := len(mat) - 1 for j >= 0 { totalSum += mat[i][i] if i != j { totalSum += mat[i][j] } i++ j-- } return totalSum }
luke.rickard
· 3 years ago
anyone else getting this error when trying to run this ?
Unknown Error - Check your Input
kimsuyon2013
· 3 years ago
Hello please fix this error! My code is correct (copy & pasted to Leetcode) but am not able to run on the code editor due to an error.
Leopoldo Hernandez
· 2 years ago
""" My solution: Time Complexity: The time complexity is O(n), where n is the number of elements in a row. The function iterates through each row and performs constant-time operations for each element. Space Complexity: The space complexity is O(1). The function uses a constant amount of space regardless of the input size. There are only a few variables (total_sum, diagonal_top_to_bottom_sum, diagonal_bottom_to_top_sum, matrix_length) used. """ class Solution: def diagonalSum(self, mat): total_sum = 0 # Initialize the total sum diagonal_top_to_bottom_sum = 0 diagonal_bottom_to_top_sum = 0 matrix_length = len(mat[0]) # provide length of elements in row print(f"matrix_length: {matrix_length}") for row_idx, row in enumerate(mat):