Modify a binary array to Bitwise AND of all elements as 1
Given an array, a[] consists of only 0 and 1. The task is to check if it is possible to transform the array such that the AND value between every pair of indices is 1. The only operation allowed is to:
- Take two indices i and j and replace the a[i] and a[j] with a[i] | a[j] where ‘|’ means bitwise OR operation.
If it is possible, then the output is “YES”, otherwise the output is “NO”.
Examples:
Input: arr[] = {0, 1, 0, 0, 1}
Output: Yes
Choose these pair of indices (0, 1), (1, 2), (3, 4).
Input: arr[] = {0, 0, 0}
Output: No
Approach:
The main observation is, if the array consists of at least one 1, then the answer will be YES, otherwise the output will be NO because OR with 1 will give us 1, as the array consists of only 0 and 1.
If there is at least one 1, then we will choose all indices with a 0 value and replace them with an OR value with the index having 1 and the OR value will always be 1.
After all operations, the array will consist of only 1 and the AND value between any pair of indices will be 1 as (1 AND 1)=1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int a[], int n)
{
for ( int i = 0; i < n; i++)
if (a[i])
return true ;
return false ;
}
int main()
{
int a[] = { 0, 1, 0, 1 };
int n = sizeof (a) / sizeof (a[0]);
check(a, n) ? cout << "YES\n"
: cout << "NO\n" ;
return 0;
}
|
Java
class GFG
{
static boolean check( int a[], int n)
{
for ( int i = 0 ; i < n; i++)
if (a[i] == 1 )
return true ;
return false ;
}
public static void main (String[] args)
{
int a[] = { 0 , 1 , 0 , 1 };
int n = a.length;
if (check(a, n) == true )
System.out.println( "YES\n" ) ;
else
System.out.println( "NO\n" );
}
}
|
Python3
def check(a, n):
for i in range (n):
if (a[i]):
return True
return False
if __name__ = = '__main__' :
a = [ 0 , 1 , 0 , 1 ]
n = len (a)
if (check(a, n)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG
{
static bool check( int []a, int n)
{
for ( int i = 0; i < n; i++)
if (a[i] == 1)
return true ;
return false ;
}
public static void Main ()
{
int []a = { 0, 1, 0, 1 };
int n = a.Length;
if (check(a, n) == true )
Console.Write( "YES\n" ) ;
else
Console.Write( "NO\n" );
}
}
|
PHP
<?php
function check( $a , $n )
{
for ( $i = 0; $i < $n ; $i ++)
if ( $a [ $i ])
return true;
return false;
}
$a = array (0, 1, 0, 1);
$n = sizeof( $a );
if (check( $a , $n ))
echo "YES\n" ;
else
echo "NO\n" ;
?>
|
Javascript
<script>
function check(a, n)
{
for ( var i = 0; i < n; i++)
if (a[i])
return true ;
return false ;
}
var a = [0, 1, 0, 1 ];
var n = a.length;
check(a, n) ? document.write( "YES" )
: document.write( "NO\n" );
</script>
|
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
15 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...