Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3 4 5 6 9 8 9
The left-to-right diagonal =1+5+9=15. The right to left diagonal = 3+5+9=17. Their absolute difference is |15-17|=2.
Function description
Complete the diagonalDifference function in the editor below.
diagonalDifference takes the following parameter:
- int arr[n][m]: an array of integers
Return
- int: the absolute diagonal difference
Input Format
The first line contains a single integer, n, the number of rows and columns in the square matrix arr .
Each of the next lines describes a row,a[i] , and consists of space-separated integers a[i][j].
Constraints
- -100<=a[i][j]<=100
Output Format
Return the absolute difference between the sums of the matrix’s two diagonals as a single integer.
Sample Input
3 11 2 4 4 5 6 10 8 -12
Sample Output
15
Explanation
The primary diagonal is:
11 5 -12
Sum across the primary diagonal: 11 + 5 – 12 = 4
The secondary diagonal is:
4 5 10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 – 19| = 15
Implementation
def diagonalDifference(arr): n = len(arr) left_to_right_sum = sum(arr[i][i] for i in range(n)) right_to_left_sum = sum(arr[i][n - 1 - i] for i in range(n)) return abs(left_to_right_sum - right_to_left_sum) # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [9, 8, 9] ] result = diagonalDifference(matrix) print("Absolute Diagonal Difference:", result)
Time Complexity
In the given solution:
- Calculating the sum of the left-to-right diagonal involves iterating through the elements along the diagonal once. The
sum
function itself has a linear time complexity in the number of elements, which isO(n)
wheren
is the size of the diagonal. - Calculating the sum of the right-to-left diagonal also involves iterating through the elements along the diagonal once. Similar to the left-to-right diagonal, the
sum
function has a linear time complexity, which isO(n)
. - The
abs
function has a constant time complexity, as it simply performs a mathematical operation.
Important Notice
If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com
For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.