I'm trying some HackerRank challenges to kill some time and I came across an easy exercise where I'm required to calculate the absolute difference between the sums of a square matrix diagonals. I really believe it's an easy exercise and should've taken little time to finish, but my algorithm doesn't seem to work for some reason as I keep getting random values for my output.
Here's my code:
int diagonalDifference(vector<vector<int>> arr) {
int d1, d2, i = 0;
int size = arr.size();
for (i ; i < size ; i++){
d1 += arr[i][i];
d2 += arr[(size - 1) - i][i];
}
return abs(d1 - d2);}
My algorithm is simple and straight forward, it calculates both diagonals in the same for loop which only iterates/repeats for as many rows/columns the matrix has (because it's a square matrix).
Link to the exercise: https://www.hackerrank.com/challenges/diagonal-difference/problem
*Please note that it's in C++.
You are using d1
, and d2
uninitialized in the loop, which invokes undefined behavior. You need to initialize them like this:
int d1 = 0, d2 = 0, i = 0;
Note that if you turn on as many warnings as possible, the compiler will warn you about these kinds of mistakes.