Count of columns with odd number of 1s
Given an N * M 2D binary matrix, the task is to find the count of columns having odd number of 1s.
Examples:
Input: mat[][] = {
{0, 0, 1, 0},
{1, 0, 0, 1},
{1, 1, 1, 0}}
Output: 2
Column 2 and 4 are the only columns
having odd number of 1’s.
Input: mat[][] = {
{1, 1, 0, 0, 1, 1},
{0, 1, 0, 1, 0, 0},
{1, 1, 1, 0, 1, 0}}
Output: 4
Approach: Find the sum of all the columns of the matrix separately. The columns having an odd sum are the columns which have an odd number of 1s.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
const int col = 4;
const int row = 3;
int countOddColumn( int arr[row][col])
{
int sum[col] = { 0 };
for ( int i = 0; i < col; i++) {
for ( int j = 0; j < row; j++) {
sum[i] += arr[j][i];
}
}
int count = 0;
for ( int i = 0; i < col; i++) {
if (sum[i] % 2 == 1) {
count++;
}
}
return count;
}
int main()
{
int arr[row][col] = { { 0, 0, 1, 0 },
{ 1, 0, 0, 1 },
{ 1, 1, 1, 0 } };
cout << countOddColumn((arr));
return 0;
}
|
Java
class GFG
{
static int col = 4 ;
static int row = 3 ;
static int countOddColumn( int arr[][])
{
int []sum = new int [col];
for ( int i = 0 ; i < col; i++)
{
for ( int j = 0 ; j < row; j++)
{
sum[i] += arr[j][i];
}
}
int count = 0 ;
for ( int i = 0 ; i < col; i++)
{
if (sum[i] % 2 == 1 )
{
count++;
}
}
return count;
}
public static void main(String []args)
{
int arr[][] = {{ 0 , 0 , 1 , 0 },
{ 1 , 0 , 0 , 1 },
{ 1 , 1 , 1 , 0 }};
System.out.println(countOddColumn((arr)));
}
}
|
Python3
col = 4
row = 3
def countOddColumn(arr):
sum = [ 0 for i in range (col)]
for i in range (col):
for j in range (row):
sum [i] + = arr[j][i]
count = 0
for i in range (col):
if ( sum [i] % 2 = = 1 ):
count + = 1
return count
arr = [[ 0 , 0 , 1 , 0 ],
[ 1 , 0 , 0 , 1 ],
[ 1 , 1 , 1 , 0 ]]
print (countOddColumn((arr)))
|
C#
using System;
class GFG
{
static int col = 4;
static int row = 3;
static int countOddColumn( int [,]arr)
{
int []sum = new int [col];
for ( int i = 0; i < col; i++)
{
for ( int j = 0; j < row; j++)
{
sum[i] += arr[j, i];
}
}
int count = 0;
for ( int i = 0; i < col; i++)
{
if (sum[i] % 2 == 1)
{
count++;
}
}
return count;
}
public static void Main()
{
int [,]arr = {{ 0, 0, 1, 0 },
{ 1, 0, 0, 1 },
{ 1, 1, 1, 0 }};
Console.WriteLine(countOddColumn((arr)));
}
}
|
Javascript
<script>
const col = 4;
const row = 3;
function countOddColumn(arr) {
let sum = new Array(col).fill(0);
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
sum[i] += arr[j][i];
}
}
let count = 0;
for (let i = 0; i < col; i++) {
if (sum[i] % 2 == 1) {
count++;
}
}
return count;
}
let arr = [[0, 0, 1, 0],
[1, 0, 0, 1],
[1, 1, 1, 0]];
document.write(countOddColumn((arr)))
</script>
|
Time Complexity: O(row * col).
Auxiliary Space: O(col).
Last Updated :
13 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...