DEV Community

Honey
Honey

Posted on

16 2

HackerRank Diagonal Difference Solution

Problem Statement

Given a square matrix[NxN], calculate the absolute difference between the sums of its diagonals.

Sample Input

3
11  2  4
4   5  6
10  8 -12
Enter fullscreen mode Exit fullscreen mode

Sample Output

15
Enter fullscreen mode Exit fullscreen mode

Diagonal(Primary Diagonal)

11
  5
   -12
Enter fullscreen mode Exit fullscreen mode

Anti-Diagonal(Secondary Diagonal)

    4
  5
10
Enter fullscreen mode Exit fullscreen mode

The absolute difference of sum of Diagonal and Anti-Diagonal elements

Diagonal Sum = 11+5+(-12) = 4
Anti-Diagonal Sum = 4+5+10 = 19

Diagonal Difference : |4-19| = 15
Enter fullscreen mode Exit fullscreen mode

Let's move code side

Here's the function diagonalDifference

int diagonalDifference(vector<vector<int>> arr)  
Enter fullscreen mode Exit fullscreen mode

Here's the for loop to get the sum of diagonal and antidiagonal elements of an arrray which are stored in two variables 'diag' and 'antidiag'.

for(i=0;i<n;i++)
{
    diag+=arr[i][i];
    antidiag+=arr[i][(n-1)-i];
}
Enter fullscreen mode Exit fullscreen mode

Then we store its absolute difference in a variable 'sum' using the function 'abs()'.

sum=abs(diag-antidiag);
Enter fullscreen mode Exit fullscreen mode

Here's the entire function 'diagonalDifference'.

int diagonalDifference(vector<vector<int>> arr) 
{
    int n=arr.size(),diag=0,antidiag=0,sum=0,i;
    for(i=0;i<n;i++)
    {
        diag+=arr[i][i];
        antidiag+=arr[i][(n-1)-i];
    }
    sum=abs(diag-antidiag);
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

In the main function we basically take in array elements and then pass it to our 'diaginalDifference' function and store it in a variable 'result'

You can also solve the problem with or without using vector. But since in HackerRank the problem is to be solved with vector, here's the solution for that.

For doing it without vector array, the logic behind remains the same but things like storage, calculation process, time complexity etc changes

Here's the complete program

int diagonalDifference(vector<vector<int>> arr) 
{
    int n=arr.size(),diag=0,antidiag=0,sum=0,i;
    for(i=0;i<n;i++)
    {
        diag+=arr[i][i];
        antidiag+=arr[i][(n-1)-i];
    }
    sum=abs(diag-antidiag);
    return sum;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string n_temp;
    getline(cin, n_temp);

    int n = stoi(ltrim(rtrim(n_temp)));

    vector<vector<int>> arr(n);

    for (int i = 0; i < n; i++) {
        arr[i].resize(n);

        string arr_row_temp_temp;
        getline(cin, arr_row_temp_temp);

        vector<string> arr_row_temp = split(rtrim(arr_row_temp_temp));

        for (int j = 0; j < n; j++) {
            int arr_row_item = stoi(arr_row_temp[j]);

            arr[i][j] = arr_row_item;
        }
    }

    int result = diagonalDifference(arr);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}

Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay