Diagonal Difference - HackerRank Problem Solving

Featured image

Diagonal Difference is easy-level Python problem that requires basic knowledge of Array. In this post, we will provide a Python solution for Diagonal Difference.

Problem Statement and Explanation

Given a square matrix, calculate the absolute difference between the sums of its diagonals. Suppose, we have the following matrix arr:

1 2 3
4 5 6
7 8 9

Diagonal of the above matrix are:

1 5 9
3 5 7

Their absolute difference is:

|15 - 17| = 2

Input Format

Output Format

Diagonal Difference Solution in Python

Explanation of Solution in Python

The function diagonalDifference() takes a square matrix arr as input and returns the absolute difference between the sums of the two diagonals of the matrix.

Diagonal Difference Solution in C++

Explanation of Solution in C++

Time complexity: The time complexity is the amount of time it takes to execute the code. In this case, the code iterates over all the rows in the matrix, so the time complexity is O(n), where n is the number of rows in the matrix.

Space complexity: The space complexity is the amount of memory that the code uses. In this case, the code only uses three variables, so the space complexity is O(1).