You are viewing a single comment's thread. Return to all comments →
Python Brute Force Solution
For the left-to-right diagonal: Loop through all elements, sum elements where row index == column index.
For the right-to-left diagonal: Loop through all elements, sum elements where row index + column index == n-1.
def diagonalDifference(arr): n = len(arr) left_diag = 0 right_diag = 0 for i in range(n): for j in range(n): if i == j: left_diag += arr[i][j] if i + j == n-1: right_diag += arr[i][j] return abs(left_diag - right_diag)
Time Complexity: O(n²), two nested loops. Space Complexity: O(1)
Optimal Solution You don't need to traverse every element, each diagonal has only n elements (one per row/column).
Access the diagonals directly using index formulas in a single loop.
def diagonalDifference(arr): n = len(arr) left_diag = 0 right_diag = 0 for i in range(n): left_diag += arr[i][i] right_diag += arr[i][n-i-1] return abs(left_diag - right_diag)
Time Complexity: O(n), just one pass Space Complexity: O(1) >
.
Seems like cookies are disabled on this browser, please enable them to open this website
Diagonal Difference
You are viewing a single comment's thread. Return to all comments →
Python Brute Force Solution
For the left-to-right diagonal: Loop through all elements, sum elements where row index == column index.
For the right-to-left diagonal: Loop through all elements, sum elements where row index + column index == n-1.
Time Complexity: O(n²), two nested loops. Space Complexity: O(1)
Optimal Solution You don't need to traverse every element, each diagonal has only n elements (one per row/column).
Access the diagonals directly using index formulas in a single loop.
Time Complexity: O(n), just one pass Space Complexity: O(1) >
.