Diagonal Difference

Leena Patel
2 min readJan 20, 2024

--

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 [17–15]=2.

Function description

Complete the diagonalDifference function in the editor below.

diagonal Difference 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, , and consists of space-separated integers .

Constraints : -100≤arr[i][j]≤100

Output Format

Return the absolute difference between the sums of the matrix’s two diagonals as a single integer.

Sample Input (n) : 3

11 2 4
4 5 6
10 8 -12

Sum across the primary diagonal: 11 + 5–12 = 4

Sum across the secondary diagonal: 4 + 5 + 10 = 19

Difference: |4–19| = 15

Note: |x| is the absolute value of x

Understanding :

Primary diagonal element : array[0][0] to array[N-1][N-1]

11 2 4
4 5 6
10 8 -12

i==j

array[0][0]=11

array[1][1]=5

array[2][2]=-12

Secondary diagonal element : array[N-1][0] to array[0][N-1]

i+j=n-1

array[2][0]=10

array[1][1]=5

array[0][2]=4

1)Solution

Time Complexity — O(n*2)

Space Complexity — O(1)

--

--