2 min to read
Diagonal Difference - HackerRank Problem Solving
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
- n: an integer, the number of rows and columns in the square matrix arr
- arr: a two-dimensional array of integers
Output Format
- int: the absolute diagonal difference
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.
- A for loop is used to iterate over all the rows in the matrix.
- In each iteration, the current element at index
arr[i][i]
is added tod1
. This is because the element at indexarr[i][i]
is located on the main diagonal of the matrix. - The current element at index
arr[i][n-i-1]
is added tod2
. This is because the element at indexarr[i][n-i-1]
is located on the secondary diagonal of the matrix. - After the for loop, the absolute difference between
d1
andd2
is returned.
Diagonal Difference Solution in C++
Explanation of Solution in C++
- The variable
s1
stores the sum of the elements on the main diagonal of the matrix. The main diagonal is the diagonal that runs from the top left corner to the bottom right corner of the matrix. - The variable
s2
stores the sum of the elements on the secondary diagonal of the matrix. The secondary diagonal is the diagonal that runs from the top right corner to the bottom left corner of the matrix. - The variable
n
stores the number of rows in the matrix. - A for loop is used to iterate over all the rows in the matrix. In each iteration, the current element is added to either
s1
ors2
, depending on whether it is on the main diagonal or the secondary diagonal. - Finally, the absolute difference between
s1
ands2
is returned.
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).