Open In App

# Count positions in Binary Matrix having equal count of set bits in corresponding row and column

Given a boolean matrix mat[][] of size M * N, the task is to print the count of indices from the matrix whose corresponding row and column contain an equal number of set bits.

Examples:

Input; mat[][] = {{0, 1}, {1, 1}}
Output: 2
Explanation:
Position (0, 0) contains 1 set bit in corresponding row {(0, 0), (0, 1)} and column {(0, 0), (1, 0)}.
Position (1, 1) contains 2 set bits in corresponding row {(1, 0), (1, 1)} and column {(0, 1), (1, 1)}.

Input: mat[][] = {{0, 1, 1, 0}, {0, 1, 0, 0}, {1, 0, 1, 0}}
Output: 5

Naive Approach: The simplest approach to solve is to count and store the number of set bits present in the elements of each row and column of the given matrix. Then, traverse the matrix and for each position, check if the count of set bits of both the row and column is equal or not. For every index for which the above condition is found to be true, increment count. Print the final value of count after complete traversal of the matrix.

Time Complexity: O(N2)
Auxiliary Space: O(N2)

Efficient Approach: To optimize the above approach, follow the steps below:

• Initialize two temporary arrays row[] and col[] of sizes N and M respectively.
• Traverse the matrix mat[][]. Check for every index (i, j), if mat[i][j] is equal to 1 or not. If found to be true, increment row[i] and col[j] by 1.
• Traverse the matrix mat[][] again. Check for every index (i, j), if row[i] and col[j] are equal or not. If found to be true, increment count.
• Print the final value of count.

Below is the implementation of the above approach:

## C++14

 `// C++14 program to implement``// above approach``#include ``using` `namespace` `std;` `// Function to return the count of indices in``// from the given binary matrix having equal``// count of set bits in its row and column``int` `countPosition(vector> mat)``{``    ``int` `n = mat.size();``    ``int` `m = mat[0].size();` `    ``// Stores count of set bits in``    ``// corresponding column and row``    ``vector<``int``> row(n);``    ``vector<``int``> col(m);` `    ``// Traverse matrix``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ` `            ``// Since 1 contains a set bit``            ``if` `(mat[i][j] == 1)``            ``{``                ` `                ``// Update count of set bits``                ``// for current row and col``                ``col[j]++;``                ``row[i]++;``            ``}``        ``}``    ``}` `    ``// Stores the count of``    ``// required indices``    ``int` `count = 0;` `    ``// Traverse matrix``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ` `            ``// If current row and column``            ``// has equal count of set bits``            ``if` `(row[i] == col[j])``            ``{``                ``count++;``            ``}``        ``}``    ``}` `    ``// Return count of``    ``// required position``    ``return` `count;``}` `// Driver Code``int` `main()``{``    ``vector> mat = { { 0, 1 },``                                ``{ 1, 1 } };` `    ``cout << (countPosition(mat));``}` `// This code is contributed by mohit kumar 29`

## Java

 `// Java Program to implement``// above approach` `import` `java.util.*;``import` `java.lang.*;` `class` `GFG {` `    ``// Function to return the count of indices in``    ``// from the given binary matrix having equal``    ``// count of set bits in its row and column``    ``static` `int` `countPosition(``int``[][] mat)``    ``{` `        ``int` `n = mat.length;``        ``int` `m = mat[``0``].length;` `        ``// Stores count of set bits in``        ``// corresponding column and row``        ``int``[] row = ``new` `int``[n];``        ``int``[] col = ``new` `int``[m];` `        ``// Traverse matrix``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {` `                ``// Since 1 contains a set bit``                ``if` `(mat[i][j] == ``1``) {` `                    ``// Update count of set bits``                    ``// for current row and col``                    ``col[j]++;``                    ``row[i]++;``                ``}``            ``}``        ``}` `        ``// Stores the count of``        ``// required indices``        ``int` `count = ``0``;` `        ``// Traverse matrix``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {` `                ``// If current row and column``                ``// has equal count of set bits``                ``if` `(row[i] == col[j]) {``                    ``count++;``                ``}``            ``}``        ``}` `        ``// Return count of``        ``// required position``        ``return` `count;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(``        ``String[] args)``    ``{` `        ``int` `mat[][] = { { ``0``, ``1` `},``                        ``{ ``1``, ``1` `} };` `        ``System.out.println(``            ``countPosition(mat));``    ``}``}`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to return the count``# of indices in from the given``# binary matrix having equal``# count of set bits in its``# row and column``def` `countPosition(mat):``    ` `    ``n ``=` `len``(mat)``    ``m ``=` `len``(mat[``0``])`` ` `    ``# Stores count of set bits in``    ``# corresponding column and row``    ``row ``=` `[``0``] ``*` `n``    ``col ``=` `[``0``] ``*` `m`` ` `    ``# Traverse matrix``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``             ` `            ``# Since 1 contains a set bit``            ``if` `(mat[i][j] ``=``=` `1``):``                 ` `                ``# Update count of set bits``                ``# for current row and col``                ``col[j] ``+``=` `1``                ``row[i] ``+``=` `1``        ` `    ``# Stores the count of``    ``# required indices``    ``count ``=` `0`` ` `    ``# Traverse matrix``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``             ` `            ``# If current row and column``            ``# has equal count of set bits``            ``if` `(row[i] ``=``=` `col[j]):``                ``count ``+``=` `1`` ` `    ``# Return count of``    ``# required position``    ``return` `count`` ` `# Driver Code``mat ``=` `[ [ ``0``, ``1` `],``        ``[ ``1``, ``1` `] ]`` ` `print``(countPosition(mat))` `# This code is contributed by sanjoy_62`

## C#

 `// C# Program to implement``// above approach``using` `System;``class` `GFG{` `// Function to return the count of indices in``// from the given binary matrix having equal``// count of set bits in its row and column``static` `int` `countPosition(``int``[,] mat)``{` `  ``int` `n = mat.GetLength(0);``  ``int` `m = mat.GetLength(1);` `  ``// Stores count of set bits in``  ``// corresponding column and row``  ``int``[] row = ``new` `int``[n];``  ``int``[] col = ``new` `int``[m];` `  ``// Traverse matrix``  ``for` `(``int` `i = 0; i < n; i++)``  ``{``    ``for` `(``int` `j = 0; j < m; j++)``    ``{``      ``// Since 1 contains a set bit``      ``if` `(mat[i, j] == 1)``      ``{``        ``// Update count of set bits``        ``// for current row and col``        ``col[j]++;``        ``row[i]++;``      ``}``    ``}``  ``}` `  ``// Stores the count of``  ``// required indices``  ``int` `count = 0;` `  ``// Traverse matrix``  ``for` `(``int` `i = 0; i < n; i++)``  ``{``    ``for` `(``int` `j = 0; j < m; j++)``    ``{``      ``// If current row and column``      ``// has equal count of set bits``      ``if` `(row[i] == col[j])``      ``{``        ``count++;``      ``}``    ``}``  ``}` `  ``// Return count of``  ``// required position``  ``return` `count;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``  ``int` `[,]mat = {{0, 1},``                ``{1, 1}};``  ``Console.WriteLine(countPosition(mat));``}``}` `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output

```2

```

Time Complexity: O(N * M)
Auxiliary Space: O(N+M)

#### Algorithm

1. Initialize count to zero
2. Iterate over each cell (i, j) in the matrix
3.Initialize row_sum and col_sum to zero
4. Iterate over each cell in the ith row and jth column
a. If the cell is set, increment row_sum and col_sum
5.If row_sum is equal to col_sum, increment count
6. Return count

## C++

 `#include ``#include ``int` `GFG(std::vector>& matrix) {``    ``int` `count = 0;``    ``for` `(``int` `i = 0; i < matrix.size(); ++i) {``        ``for` `(``int` `j = 0; j < matrix[0].size(); ++j) {``            ``int` `row_sum = 0;``            ``int` `col_sum = 0;``            ``for` `(``int` `k = 0; k < matrix.size(); ++k) {``                ``row_sum += matrix[i][k];``                ``col_sum += matrix[k][j];``            ``}``            ``if` `(row_sum == col_sum) {``                ``count += 1;``            ``}``        ``}``    ``}``    ``return` `count;``}``int` `main() {``    ``std::vector> matrix = {{0, 1}, {1, 1}};``    ``std::cout <

## Java

 `import` `java.io.*;``import` `java.util.*;` `public` `class` `Main {``    ``public` `static` `int` `GFG(``int``[][] matrix) {``        ``int` `count = ``0``;``        ``int` `rows = matrix.length;``        ``int` `cols = matrix[``0``].length;``        ``for` `(``int` `i = ``0``; i < rows; ++i) {``            ``for` `(``int` `j = ``0``; j < cols; ++j) {``                ``int` `rowSum = ``0``;``                ``int` `colSum = ``0``;``                ``for` `(``int` `k = ``0``; k < rows; ++k) {``                    ``rowSum += matrix[i][k];``                    ``colSum += matrix[k][j];``                ``}``                ``if` `(rowSum == colSum) {``                    ``count += ``1``;``                ``}``            ``}``        ``}``        ``return` `count;``    ``}``    ``public` `static` `void` `main(String[] args) {``        ``int``[][] matrix = {{``0``, ``1``}, {``1``, ``1``}};``        ``int` `result = GFG(matrix);``        ``System.out.println(result);``    ``}``}`

## Python3

 `def` `count_positions(matrix):``    ``count ``=` `0``    ``for` `i ``in` `range``(``len``(matrix)):``        ``for` `j ``in` `range``(``len``(matrix[``0``])):``            ``row_sum ``=` `0``            ``col_sum ``=` `0``            ``for` `k ``in` `range``(``len``(matrix)):``                ``row_sum ``+``=` `matrix[i][k]``                ``col_sum ``+``=` `matrix[k][j]``            ``if` `row_sum ``=``=` `col_sum:``                ``count ``+``=` `1``    ``return` `count``matrix ``=` `[ [ ``0``, ``1` `],``        ``[ ``1``, ``1` `] ]``print``( count_positions(matrix))`

## Javascript

 `function` `GFG(matrix) {``    ``let count = 0;``    ``const rows = matrix.length;``    ``const cols = matrix[0].length;``    ` `    ``// Loop through each element in the matrix``    ``for` `(let i = 0; i < rows; ++i) {``        ``for` `(let j = 0; j < cols; ++j) {``            ``let rowSum = 0;``            ``let colSum = 0;``            ` `            ``// Calculate the sum of elements in the current row and column``            ``for` `(let k = 0; k < rows; ++k) {``                ``rowSum += matrix[i][k];``                ``colSum += matrix[k][j];``            ``}``            ` `            ``// If the sum of the current row and column are equal, increment count``            ``if` `(rowSum === colSum) {``                ``count += 1;``            ``}``        ``}``    ``}``    ` `    ``return` `count;``}` `// Main function``    ``const matrix = [[0, 1], [1, 1]];``    ``const result = GFG(matrix);``    ``console.log(result);`

Output

```2

```

Time Complexity: O(n^3), where n is the size of the matrix
Space Complexity: O(1)