I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen
O(n) time solution to find the diagonal difference of given multidimensional array.
def diagonalDifference(arr):
# arr[0][0], arr[1][1], arr[2][2]
# arr[0][2], arr[1][1], arr[2][0]
sumOfDiagonalFromLeft = 0
sumOfDiagonalFromRight = 0
pointIndexFromLeft = 0
pointIndexFromLast = len(arr)-1
for i in range(len(arr)):
sumOfDiagonalFromLeft += arr[i][pointIndexFromLeft]
# print(arr[i][pointIndexFromLeft])
pointIndexFromLeft += 1
for i in range(len(arr)):
sumOfDiagonalFromRight += arr[i][pointIndexFromLast]
# print(arr[i][pointIndexFromLast])
if pointIndexFromLast < 0:
break
else:
pointIndexFromLast -= 1
diagonalDifference = abs(sumOfDiagonalFromLeft - sumOfDiagonalFromRight)
return diagonalDifference
arr = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
print(diagonalDifference(arr))