Check if bitwise AND of any subset is power of two
Last Updated :
10 Aug, 2022
Given an array arr[] of n positive integers. The task is to check if there exist any subset of the array whose bitwise AND is a power of two (i.e 1, 2, 4, 8, 16, ...).
Note : There might be exist two or more subset of given array whose bitwise AND becomes power of two. Return YES if there exist at least one subset otherwise return NO.
Examples:
Input : n = 3, arr[] = { 12, 13, 7 }
Output : Yes
Explanation : Subset {12, 13, 7} and { 12, 7 } have Bitwise AND value 4 and 4 resepectively, which
are power of 2.
Input : n = 2, arr[] = { 10, 20 }
Output : No
Observe, for a number to be the power of 2, it should have only 1 set bit.
If n is 1, then we simply check if the number has the only single set bit.
For n is greater than one, our task becomes to choose those numbers from the array whose bitwise AND leads to an only single bit set number. To do so, we search a position, at which all elements in the set has a bit set at that position. For example, for set { 4 (100), 6 (110), 7 (111) }, at position 2 (from right to left, 0-based indexing) bit is set for all element. So, doing bitwise AND gives 4, which is a power of 2.
Below is the implementation of this approach:
Illustration :
12 --> 01100
13 --> 01101
7 --> 00111
For position = 0(from right to left, 0-based indexing), there exist 13 and 17 whose bit is setbit.
total --> 1111111111111111111111
13 --> 0000000000000000001101
7 --> 0000000000000000000111
-----------------------------
bitwise AND --> 0000000000000000000101
bitwise AND is not power of 2 so it is not a valid subset.
For position = 1, there exist only 7 whose bit is setbit.
total --> 1111111111111111111111
7 --> 0000000000000000000111
------------------------------
bitwise AND --> 0000000000000000000111
bitwise AND is not power of 2 so it is not a valid subset.
For position = 2, there exist 12, 13 and 7 whose bit is setbit.
total --> 1111111111111111111111
12 --> 0000000000000000001100
13 --> 0000000000000000001101
7 --> 0000000000000000000111
------------------------------
bitwise AND --> 0000000000000000000100
bitwise AND is power of 2 so it is a valid subset.
Similarly, we can check for remaining positions.
Algorithm :
- If size of array is 1 then simply check whether first element of array is power of 2 or not.
- Otherwise, create a variable total = 0 and make its all bits to setbit.
- Traverse from i=0 to i = 31 for every bit.
- Create a variable ans = total.
- Traverse in an array and if the bit of current element at position i is setbit then change ans variable to bitwise AND of ans and current element.
- After completion of traversal in array. Check our ans is power of two or not.
- If ans is power of two then return true. Otherwise, traverse for next bit.
- After traversing every bit if we did not found any subset then return false.
Implementation :
C++
// CPP Program to check if Bitwise AND of any
// subset is power of two
#include <bits/stdc++.h>
using namespace std;
const int NUM_BITS = 32;
// Check for power of 2 or not
bool isPowerOf2(int num)
{
return (num && !(num & (num - 1)));
}
// Check if there exist a subset whose bitwise AND
// is power of 2.
bool checkSubsequence(int arr[], int n)
{
// if there is only one element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with all bit sets.
int total = 0;
for (int i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions at which the bit is set.
for (int i = 0; i < NUM_BITS; i++) {
int ans = total;
for (int j = 0; j < n; j++) {
// include all those elements whose
// i-th bit is set
if (arr[j] & (1 << i))
ans = ans & arr[j];
}
// check for the set contains elements
// make a power of 2 or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Program
int main()
{
int arr[] = { 12, 13, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
if (checkSubsequence(arr, n))
printf("YES\n");
else
printf("NO\n");
return 0;
}
Java
// Java Program to check if Bitwise AND of any
// subset is power of two
import java.io.*;
import java.util.*;
public class GFG {
static int NUM_BITS = 32;
// Check for power of 2 or not
static boolean isPowerOf2(int num)
{
if(num != 0 && (num & (num - 1)) == 0)
return true;
return false;
}
// Check if there exist a
// subset whose bitwise AND
// is power of 2.
static boolean checkSubsequence(int []arr, int n)
{
// if there is only one
// element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with
// all bit sets.
int total = 0;
for (int i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions
// at which the bit is set.
for (int i = 0; i < NUM_BITS; i++)
{
int ans = total;
for (int j = 0; j < n; j++)
{
// include all those
// elements whose
// i-th bit is set
int p = arr[j] & (1 << i);
if (p == 0)
ans = ans & arr[j];
}
// check for the set
// contains elements
// make a power of 2
// or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Code
public static void main(String args[])
{
int []arr = {12, 13, 7};
int n = arr.length;
if (checkSubsequence(arr, n))
System.out.println("YES");
else
System.out.println("NO");
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
# Python3 Program to check if Bitwise AND of any
# subset is power of two
NUM_BITS = 32
# Check for power of 2 or not
def isPowerOf2(num):
return (num and (num & (num - 1)) == 0)
# Check if there exist a subset whose bitwise AND
# is power of 2.
def checkSubsequence(arr, n):
# if there is only one element in the set.
if (n == 1):
return isPowerOf2(arr[0])
# Finding a number with all bit sets.
total = 0
for i in range(0, NUM_BITS):
total = total | (1 << i)
# check all the positions at which the bit is set.
for i in range(0, NUM_BITS):
ans = total
for j in range(0, n):
# include all those elements whose
# i-th bit is set
if (arr[j] & (1 << i)):
ans = ans & arr[j]
# check for the set contains elements
# make a power of 2 or not
if (isPowerOf2(ans)):
return True
return False
# Driver Program
arr = [ 12, 13, 7 ]
n = len(arr)
if (checkSubsequence(arr, n)):
print ("YES\n")
else:
print ("NO\n")
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
// C# Program to check if Bitwise AND of any
// subset is power of two
using System;
using System.Collections.Generic;
class GFG {
static int NUM_BITS = 32;
// Check for power of 2 or not
static bool isPowerOf2(int num)
{
if(num != 0 && (num & (num - 1)) == 0)
return true;
return false;
}
// Check if there exist a
// subset whose bitwise AND
// is power of 2.
static bool checkSubsequence(int []arr, int n)
{
// if there is only one
// element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with
// all bit sets.
int total = 0;
for (int i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions
// at which the bit is set.
for (int i = 0; i < NUM_BITS; i++)
{
int ans = total;
for (int j = 0; j < n; j++)
{
// include all those
// elements whose
// i-th bit is set
int p = arr[j] & (1 << i);
if (p == 0)
ans = ans & arr[j];
}
// check for the set
// contains elements
// make a power of 2
// or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Code
public static void Main()
{
int []arr = {12, 13, 7};
int n = arr.Length;
if (checkSubsequence(arr, n))
Console.Write("YES\n");
else
Console.Write("NO\n");
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP Program to check if
// Bitwise AND of any subset
// is power of two
// Check for power of 2 or not
function isPowerOf2($num)
{
return ($num && !($num & ($num - 1)));
}
// Check if there exist a
// subset whose bitwise AND
// is power of 2.
function checkSubsequence($arr, $n)
{
$NUM_BITS = 32;
// if there is only one
// element in the set.
if ($n == 1)
return isPowerOf2($arr[0]);
// Finding a number with
// all bit sets.
$total = 0;
for($i = 0; $i < $NUM_BITS; $i++)
$total = $total | (1 << $i);
// check all the positions at
// which the bit is set.
for($i = 0; $i < $NUM_BITS; $i++)
{
$ans = $total;
for ($j = 0; $j < $n; $j++)
{
// include all those
// elements whose
// i-th bit is set
if ($arr[$j] & (1 << $i))
$ans = $ans & $arr[$j];
}
// check for the set
// contains elements
// make a power of 2 or not
if (isPowerOf2($ans))
return true;
}
return false;
}
// Driver Code
$arr= array(12, 13, 7);
$n = sizeof($arr) / sizeof($arr[0]);
if (checkSubsequence($arr, $n))
echo "YES";
else
echo "NO";
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript Program to check if Bitwise AND of any
// subset is power of two
var NUM_BITS = 32;
// Check for power of 2 or not
function isPowerOf2(num)
{
return (num && !(num & (num - 1)));
}
// Check if there exist a subset whose bitwise AND
// is power of 2.
function checkSubsequence(arr, n)
{
// if there is only one element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with all bit sets.
var total = 0;
for (var i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions at which the bit is set.
for (var i = 0; i < NUM_BITS; i++) {
var ans = total;
for (var j = 0; j < n; j++) {
// include all those elements whose
// i-th bit is set
if (arr[j] & (1 << i))
ans = ans & arr[j];
}
// check for the set contains elements
// make a power of 2 or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Program
var arr = [ 12, 13, 7 ];
var n = arr.length;
if (checkSubsequence(arr, n))
document.write("YES<br>");
else
document.write("NO<br>");
// This code is contributed by itsok.
</script>
Time Complexity : O(N), [(32)* (length of array) where 32 is constant time, so as per recurrence tree the time complexity is of N order]
Auxiliary Space : O(1)
Similar Reads
Check whether bitwise AND of a number with any subset of an array is zero or not
Given an array and a Number N. The task is to check whether there exists any subset of this array such that the bitwise AND of this subset with N is zero. Examples: Input : arr[] = {1, 2, 4} ; N = 3 Output : YES Explanation: The subsets are: (1, 2 ), (1, 4), (1, 2, 4) Input : arr[] = {1, 1, 1} ; N =
6 min read
Queries to check whether bitwise AND of a subarray is even or odd
Given an array arr[] of N positive integers, the task is to answer Q queries where each query consists of a range [L, R] and you have to check whether the bitwise AND of the elements from the given index range is even or odd.Examples: Input: arr[] = {1, 1, 2, 3}, Q[][] = {{1, 2}, {0, 1}} Output: Eve
10 min read
Check if a number has two adjacent set bits
Given a number you have to check whether there is pair of adjacent set bit or not.Examples : Input : N = 67 Output : Yes There is a pair of adjacent set bit The binary representation is 100011 Input : N = 5 Output : No Recommended PracticeNumbers having two adjacent set bitsTry It! A simple solution
3 min read
Count of pairs whose bitwise AND is a power of 2
Given an array arr[] of N positive integers. The task is to find the number of pairs whose Bitwise AND value is a power of 2.Examples: Input: arr[] = {2, 1, 3, 4} Output: 2 Explanation: There are 2 pairs (2, 3) and (1, 3) in this array whose Bitwise AND values are: 1. (2 & 3) = 1 = (20) 2. (1
13 min read
Sum of bitwise AND of all possible subsets of given set
Given an array, we need to calculate the Sum of Bit-wise AND of all possible subsets of the given array. Examples: Input : 1 2 3 Output : 9 For [1, 2, 3], all possible subsets are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3} Bitwise AND of these subsets are, 1 + 2 + 3 + 0 + 1 + 2 + 0 = 9. So, th
7 min read
Check if original Array Sum is Odd or Even using Bitwise AND of Array
Given an integer N denoting the size of an array and the bitwise AND (K) of all elements of the array. The task is to determine whether the total sum of the elements is odd or even or cannot be determined. Examples: Input: N = 1, K = 11Output: OddExplanation: As there is only one element in the arra
6 min read
Check whether bitwise AND of N numbers is Even or Odd
Given an array arr[] containing N numbers. The task is to check whether the bitwise-AND of the given N numbers is even or odd.Examples: Input: arr[] = { 2, 12, 20, 36, 38 } Output: Even Input: arr[] = { 3, 9, 17, 13, 15 } Output: Odd A Simple Solution is to first find the AND of the given N numbers,
7 min read
Bitwise OR of Bitwise AND of all subarrays of an array
Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are: {1}, Bitwise AND is 1.{1, 2}, Bitwise AN
7 min read
Given a HUGE number check if it's a power of two.
Find if a given number, num is the power of 2 or not. More specifically, find if the given number can be expressed as 2^k where k >= 1. Return 1 if the number is a power of 2 else return 0NOTE : A number of digits of the given number i.e (num) can be greater than 100.There are no leading zeros be
15+ min read
Count of possible pairs whose sum and bitwise XOR is given
Given two integers S and X representing the sum and bitwise XOR respectively of two integers, the task is to find the count of all such possible pairs such that their sum is equal to S and bitwise XOR is equal to X. Examples: Input: S = 9, X = 5Output: 4Explanation: (2, 7), (3, 6), (6, 3), (7, 2) co
9 min read