Grokking Data Structures & Algorithms for Coding Interviews
0% completed
Solution: Matrix Diagonal Sum (easy)
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 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 }
A
Anonymous
· 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 } }
A
Anonymous
· 3 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):
A
Anonymous
· 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.
A
Anonymous
· 3 years ago
anyone else getting this error when trying to run this ?
Unknown Error - Check your Input
Reading Progress
0%