Hackerrank Diagonal Difference (C++)

C++ :

int diagonalDifference(vector<vector<int>> arr) {
    int difference, primary = 0, secondary = 0, secondIndex = 0;

    if(arr.size() == 1){
        difference = abs(arr[0][0]);
    } else {
        for(int i = 0; i < arr.size(); i++){
            secondIndex = arr.size() - (i + 1);
            primary += arr[i][i];
            secondary += arr[i][secondIndex];

        difference = abs(primary - secondary);

    return difference;


Basically, this is like a tic tac toe puzzle. It goes something like this for a 3 by 3:

 [0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
[2][0] [2][1] [2][2]

But first, we check if the vector is size 1, which means nothing to minus, so just set the difference to the absolute of the single number in the size one vector. Then, if the vector is not size 1, for each round in the outer loop of the vector, set secondIndex to the (max vector size – round number) to get the inner loop index. Add each diagonal number from [0][0] to [n][n] to primary and each diagonal number from [0][n] to [n][0] to secondary. The difference is then the absolute of primary – secondary. This saves having a double loop, and might improve performance slightly for huge vectors.

You may also like...

2 Responses

  1. 3m n95 8511 says:

    Thank you so much for doing the job that is remarkable here,
    everybody will like your post.
    King regards,
    Thompson Zacho

Leave a Reply

Your email address will not be published. Required fields are marked *