Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Leopoldo Hernandez
My Solution in Python

Leopoldo Hernandez

Feb 6, 2024

""" 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): if ((row_idx, row_idx) == (matrix_length - row_idx - 1, row_idx)): diagonal_top_to_bottom_sum += mat[row_idx][row_idx] else: diagonal_top_to_bottom_sum += mat[row_idx][row_idx] diagonal_bottom_to_top_sum += mat[matrix_length - row_idx - 1][row_idx] total_sum = (diagonal_bottom_to_top_sum + diagonal_top_to_bottom_sum) return total_sum # Return the calculated total sum

0

0

Comments
Comments

On this page