Matrix: Given a matrix, you need to count the number of rows and columns whose sum equal to diagonal sum

Problem Statement:

Given a 2D matrix of size n*n.

You need to count the number of rows and columns whose sum equal to diagonal sum

Example:

Input:

1 7 3 
1 5 6
7 9 6

Sum of principal diagonal = 1 + 5 + 6 = 12

Sum of secondary diagonal = 3 + 5 + 7 = 13

Output: 1

Row 2 = 1 + 5 + 6 = 2

Solution Explanation:

Solution is very simple:

Count the number of rows or columns whose sum is equal to secondary or primary diagonal.

If equal increment the count and return the result.

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <unordered_map>
using namespace std;


#define n 3 // Rows


int solution(int arr[][n])
{
    int principal_diag = 0;
    int secondary_diag = 0;
    int row = 0, col = 0, count = 0;

    for (int i = 0, j = n - 1; i < n; i++, j--)
    {
        principal_diag += arr[i][i];

        secondary_diag += arr[i][j];
    }

    for (int i = 0; i < n; i++) {
        row = 0, col = 0;
        
        for (int j = 0; j < n; j++) {
            row = row + arr[i][j];
        }
        for (int j = 0; j < n; j++) {
            col = col + arr[j][i];
        }
        if ((row == principal_diag) || (row == secondary_diag)) {
            count++;
        }
        if ((col == principal_diag) || (col == secondary_diag))
            count++;
    }
    
    return count;
}

int main()
{
    int arr[n][n] = { { 1, 7, 3 },
                      { 1, 5, 6 },
                      { 7, 9, 6 } };

    cout << solution(arr) << endl;
}

Output

2
Write a Comment

Leave a Comment

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