Given an array a of size N and an integer K. The task is to find the maximum bitwise and value of elements of any subsequence of length K.
Note: a[i] <= 109
Examples:
Input: a[] = {10, 20, 15, 4, 14}, K = 4
Output: 4
{20, 15, 4, 14} is the subsequence with highest ‘&’ value.
Input: a[] = {255, 127, 31, 5, 24, 37, 15}, K = 5
Output: 8
Naive Approach: A naive approach is to recursively find the bitwise and value of all subsequences of length K and the maximum among all of them will be the answer.
// C++ code to calculate the // maximum bitwise and of // subsequence of size k. #include <bits/stdc++.h> using namespace std;
// for storing all bitwise and. vector< int > v;
// Recursive function to print all // possible subsequences for given array void subsequence( int arr[], int index, vector< int >& subarr,
int n, int k)
{ // calculate the bitwise and when reach
// at last index
if (index == n) {
if (subarr.size() == k) {
int ans = subarr[0];
for ( auto it : subarr) {
ans = ans & it;
}
v.push_back(ans); // storing the bitwise
// and to vector v.
}
return ;
}
else {
// pick the current index into the subsequence.
subarr.push_back(arr[index]);
subsequence(arr, index + 1, subarr, n, k);
subarr.pop_back();
// not picking the element into the subsequence.
subsequence(arr, index + 1, subarr, n, k);
}
} // Driver Code int main()
{ int arr[] = { 255, 127, 31, 5, 24, 37, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 5;
vector< int > vec;
subsequence(arr, 0, vec, n, k);
// maximum bitwise and is
cout << *max_element(v.begin(), v.end());
return 0;
} // This code is contributed by // Naveen Gujjar from Haryana |
// Java code to calculate the // maximum bitwise and of // subsequence of size k. import java.util.*;
class Main {
// for storing all bitwise and.
static ArrayList<Integer> v = new ArrayList<Integer>();
// Recursive function to print all
// possible subsequences for given array
static void subsequence( int [] arr, int index,
ArrayList<Integer> subarr,
int n, int k)
{
// calculate the bitwise and when reach
// at last index
if (index == n) {
if (subarr.size() == k) {
int ans = subarr.get( 0 );
for ( int it : subarr) {
ans = ans & it;
}
v.add(ans); // storing the bitwise
// and to vector v.
}
return ;
}
else {
// pick the current index into the subsequence.
subarr.add(arr[index]);
subsequence(arr, index + 1 , subarr, n, k);
subarr.remove(subarr.size() - 1 );
// not picking the element into the subsequence.
subsequence(arr, index + 1 , subarr, n, k);
}
}
// Driver Code
public static void main(String[] args)
{
int [] arr = { 255 , 127 , 31 , 5 , 24 , 37 , 15 };
int n = arr.length;
int k = 5 ;
ArrayList<Integer> vec = new ArrayList<Integer>();
subsequence(arr, 0 , vec, n, k);
// maximum bitwise and is
System.out.println(Collections.max(v));
}
} // This code is contributed by user_dtewbxkn77n |
import itertools
# for storing all bitwise and. v = []
# Recursive function to print all # possible subsequences for given array def subsequence(arr, index, subarr, n, k):
# calculate the bitwise and when reach
# at last index
if index = = n:
if len (subarr) = = k:
ans = subarr[ 0 ]
for i in range ( 1 , len (subarr)):
ans & = subarr[i]
v.append(ans) # storing the bitwise
# and to vector v.
return
else :
# pick the current index into the subsequence.
subarr.append(arr[index])
subsequence(arr, index + 1 , subarr, n, k)
subarr.pop()
# not picking the element into the subsequence.
subsequence(arr, index + 1 , subarr, n, k)
# Driver Code if __name__ = = "__main__" :
arr = [ 255 , 127 , 31 , 5 , 24 , 37 , 15 ]
n = len (arr)
k = 5
vec = []
subsequence(arr, 0 , vec, n, k)
# maximum bitwise and is
print ( max (v))
|
// C# code to calculate the // maximum bitwise and of // subsequence of size k. using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
//for storing all bitwise and. static List< int > v = new List< int >();
// Recursive function to print all
// possible subsequences for given array static void subsequence( int [] arr, int index,
List< int > subarr, int n, int k)
{ // calculate the bitwise and when reach
// at last index
if (index == n)
{
if (subarr.Count==k){
int ans=subarr[0];
foreach ( int it in subarr){
ans &= it;
}
v.Add(ans); // storing the bitwise
// and to list v.
}
return ;
}
else
{
//pick the current index into the subsequence.
subarr.Add(arr[index]);
subsequence(arr, index + 1, subarr,n,k);
subarr.RemoveAt(subarr.Count-1);
//not picking the element into the subsequence.
subsequence(arr, index + 1, subarr,n,k);
}
} // Driver Code static void Main()
{ int [] arr={ 255, 127, 31, 5, 24, 37 ,15};
int n=arr.Length;
int k=5;
List< int > vec = new List< int >();
subsequence(arr, 0, vec,n,k);
// maximum bitwise and is
Console.WriteLine(v.Max());
} } |
// Importing itertools is not necessary in JavaScript // For storing all bitwise and. let v = []; // Recursive function to print all // possible subsequences for given array function subsequence(arr, index, subarr, n, k)
{ // Calculate the bitwise and when reach
// at last index
if (index == n) {
if (subarr.length == k) {
let ans = subarr[0];
for (let i = 1; i < subarr.length; i++) {
ans &= subarr[i];
}
v.push(ans); // Storing the bitwise
// and to vector v.
}
return ;
} else {
// Pick the current index into the subsequence.
subarr.push(arr[index]);
subsequence(arr, index + 1, subarr, n, k);
subarr.pop();
// Not picking the element into the subsequence.
subsequence(arr, index + 1, subarr, n, k);
}
} // Driver Code let arr = [255, 127, 31, 5, 24, 37, 15]; let n = arr.length; let k = 5; let vec = []; subsequence(arr, 0, vec, n, k); // Maximum bitwise and is console.log(Math.max(...v)); |
8
Time Complexity: O(k*(2^n)) where k is the maximum subsequence length and n is the size of the array.
Auxiliary space: O(2^n) where n is the size of the array.
Approach 1: An efficient approach is to solve it using bit properties. Below are the steps to solve the problem:
- Iterate from the left(initially left = 31 as 232 > 109 ) till we find > K numbers in the vector temp (initially temp = arr) whose i-th bit is set. Update the new set of numbers to temp array
- If we do not get > K numbers, the & value of any K elements in the temp array will be the maximum & value possible.
- Repeat Step-1 with left re-initialized as first-bit + 1.
Below is the implementation of the above approach:
// C++ program to find the sum of // the addition of all possible subsets. #include <bits/stdc++.h> using namespace std;
// Function to perform step-1 vector< int > findSubset(vector< int >& temp, int & last, int k)
{ vector< int > ans;
// Iterate from left till 0
// till we get a bit set of K numbers
for ( int i = last; i >= 0; i--) {
int cnt = 0;
// Count the numbers whose
// i-th bit is set
for ( auto it : temp) {
int bit = it & (1 << i);
if (bit > 0)
cnt++;
}
// If the array has numbers>=k
// whose i-th bit is set
if (cnt >= k) {
for ( auto it : temp) {
int bit = it & (1 << i);
if (bit > 0)
ans.push_back(it);
}
// Update last
last = i - 1;
// Return the new set of numbers
return ans;
}
}
return ans;
} // Function to find the maximum '&' value // of K elements in subsequence int findMaxiumAnd( int a[], int n, int k)
{ int last = 31;
// Temporary arrays
vector< int > temp1, temp2;
// Initially temp = arr
for ( int i = 0; i < n; i++) {
temp2.push_back(a[i]);
}
// Iterate till we have >=K elements
while (( int )temp2.size() >= k) {
// Temp array
temp1 = temp2;
// Find new temp array if
// K elements are there
temp2 = findSubset(temp2, last, k);
}
// Find the & value
int ans = temp1[0];
for ( int i = 0; i < k; i++)
ans = ans & temp1[i];
return ans;
} // Driver Code int main()
{ int a[] = { 255, 127, 31, 5, 24, 37, 15 };
int n = sizeof (a) / sizeof (a[0]);
int k = 4;
cout << findMaxiumAnd(a, n, k);
} |
// Java program to find the sum of // the addition of all possible subsets. import java.util.*;
class GFG
{ static int last;
// Function to perform step-1 static Vector<Integer>
findSubset(Vector<Integer> temp, int k)
{ Vector<Integer> ans = new Vector<Integer>();
// Iterate from left till 0
// till we get a bit set of K numbers
for ( int i = last; i >= 0 ; i--)
{
int cnt = 0 ;
// Count the numbers whose
// i-th bit is set
for (Integer it : temp)
{
int bit = it & ( 1 << i);
if (bit > 0 )
cnt++;
}
// If the array has numbers>=k
// whose i-th bit is set
if (cnt >= k)
{
for (Integer it : temp)
{
int bit = it & ( 1 << i);
if (bit > 0 )
ans.add(it);
}
// Update last
last = i - 1 ;
// Return the new set of numbers
return ans;
}
}
return ans;
} // Function to find the maximum '&' value // of K elements in subsequence static int findMaxiumAnd( int a[], int n, int k)
{ last = 31 ;
// Temporary arrays
Vector<Integer> temp1 = new Vector<Integer>();
Vector<Integer> temp2 = new Vector<Integer>();;
// Initially temp = arr
for ( int i = 0 ; i < n; i++)
{
temp2.add(a[i]);
}
// Iterate till we have >=K elements
while (( int )temp2.size() >= k)
{
// Temp array
temp1 = temp2;
// Find new temp array if
// K elements are there
temp2 = findSubset(temp2, k);
}
// Find the & value
int ans = temp1.get( 0 );
for ( int i = 0 ; i < k; i++)
ans = ans & temp1.get(i);
return ans;
} // Driver Code public static void main(String[] args)
{ int a[] = { 255 , 127 , 31 , 5 , 24 , 37 , 15 };
int n = a.length;
int k = 4 ;
System.out.println(findMaxiumAnd(a, n, k));
} } // This code is contributed by 29AjayKumar |
# Python3 program to find the sum of # the addition of all possible subsets. last = 31
# Function to perform step-1 def findSubset(temp, k):
global last
ans = []
# Iterate from left till 0
# till we get a bit set of K numbers
for i in range (last, - 1 , - 1 ):
cnt = 0
# Count the numbers whose
# i-th bit is set
for it in temp:
bit = it & ( 1 << i)
if (bit > 0 ):
cnt + = 1
# If the array has numbers>=k
# whose i-th bit is set
if (cnt > = k):
for it in temp:
bit = it & ( 1 << i)
if (bit > 0 ):
ans.append(it)
# Update last
last = i - 1
# Return the new set of numbers
return ans
return ans
# Function to find the maximum '&' value # of K elements in subsequence def findMaxiumAnd(a, n, k):
global last
# Temporary arrays
temp1, temp2, = [], []
# Initially temp = arr
for i in range (n):
temp2.append(a[i])
# Iterate till we have >=K elements
while len (temp2) > = k:
# Temp array
temp1 = temp2
# Find new temp array if
# K elements are there
temp2 = findSubset(temp2, k)
# Find the & value
ans = temp1[ 0 ]
for i in range (k):
ans = ans & temp1[i]
return ans
# Driver Code a = [ 255 , 127 , 31 , 5 , 24 , 37 , 15 ]
n = len (a)
k = 4
print (findMaxiumAnd(a, n, k))
# This code is contributed by Mohit Kumar |
// C# program to find the sum of // the addition of all possible subsets. using System;
using System.Collections.Generic;
class GFG
{ static int last;
// Function to perform step-1 static List< int >findSubset(List< int > temp, int k)
{ List< int > ans = new List< int >();
// Iterate from left till 0
// till we get a bit set of K numbers
for ( int i = last; i >= 0; i--)
{
int cnt = 0;
// Count the numbers whose
// i-th bit is set
foreach ( int it in temp)
{
int bit = it & (1 << i);
if (bit > 0)
cnt++;
}
// If the array has numbers>=k
// whose i-th bit is set
if (cnt >= k)
{
foreach ( int it in temp)
{
int bit = it & (1 << i);
if (bit > 0)
ans.Add(it);
}
// Update last
last = i - 1;
// Return the new set of numbers
return ans;
}
}
return ans;
} // Function to find the maximum '&' value // of K elements in subsequence static int findMaxiumAnd( int []a, int n, int k)
{ last = 31;
// Temporary arrays
List< int > temp1 = new List< int >();
List< int > temp2 = new List< int >();;
// Initially temp = arr
for ( int i = 0; i < n; i++)
{
temp2.Add(a[i]);
}
// Iterate till we have >=K elements
while (( int )temp2.Count >= k)
{
// Temp array
temp1 = temp2;
// Find new temp array if
// K elements are there
temp2 = findSubset(temp2, k);
}
// Find the & value
int ans = temp1[0];
for ( int i = 0; i < k; i++)
ans = ans & temp1[i];
return ans;
} // Driver Code public static void Main(String[] args)
{ int []a = { 255, 127, 31, 5, 24, 37, 15 };
int n = a.Length;
int k = 4;
Console.WriteLine(findMaxiumAnd(a, n, k));
} } // This code is contributed by Rajput-Ji |
<script> // Javascript program to find the sum of // the addition of all possible subsets. // Function to perform step-1 function findSubset(temp,k)
{ let ans = [];
// Iterate from left till 0
// till we get a bit set of K numbers
for (let i = last; i >= 0; i--)
{
let cnt = 0;
// Count the numbers whose
// i-th bit is set
for (let it=0;it< temp.length;it++)
{
let bit = temp[it] & (1 << i);
if (bit > 0)
cnt++;
}
// If the array has numbers>=k
// whose i-th bit is set
if (cnt >= k)
{
for (let it=0;it< temp.length;it++)
{
let bit = temp[it] & (1 << i);
if (bit > 0)
ans.push(temp[it]);
}
// Update last
last = i - 1;
// Return the new set of numbers
return ans;
}
}
return ans;
} // Function to find the maximum '&' value // of K elements in subsequence function findMaxiumAnd(a,n,k)
{ last = 31;
// Temporary arrays
let temp1 = [];
let temp2 = [];
// Initially temp = arr
for (let i = 0; i < n; i++)
{
temp2.push(a[i]);
}
// Iterate till we have >=K elements
while (temp2.length >= k)
{
// Temp array
temp1 = temp2;
// Find new temp array if
// K elements are there
temp2 = findSubset(temp2, k);
}
// Find the & value
let ans = temp1[0];
for (let i = 0; i < k; i++)
ans = ans & temp1[i];
return ans;
} // Driver Code let a=[255, 127, 31, 5, 24, 37, 15 ]; let n = a.length; let k = 4; document.write(findMaxiumAnd(a, n, k)); // This code is contributed by unknown2108 </script> |
24
Time Complexity: O(N*N), as we are using a loop to traverse N times and in each traversal we are calling the findSubset function which will cost O (N) time. Where N is the number of elements in the array.
Auxiliary Space: O(N), as we are using extra space for the temp array. Where N is the number of elements in the array.
Approach 2:
The idea is based on the property of AND operator. AND operation of any two bits results in 1 if both bits are 1 else if any bit is 0 then result is 0. So We start from the MSB and check whether we have a minimum of K elements of array having set value. If yes then that MSB will be part of our solution and be added to result otherwise we will discard that bit. Similarly,iterating from MSB to LSB (32 to 1) for bit position we can easily check which bit will be part of our solution and will keep adding all such bits to our solution.
Following are the steps to implement above idea :
- Initialize result variable with 0 .
- Run a outer for loop from j : 31 to 0 (for every bit)
- Initialize temporary variable with ( res | (1<<j) ) .
- Initialize count variable with 0 .
- Run a inner for loop from i : 0 to n-1 and check
- if ( ( temporary & A[i] ) == temporary ) then count++ .
- After inner for loop gets over then check :
- if ( count >= K ) then update result with temporary .
- After outer for loops ends return result .
- Print result .
Below is the code for above approach .
#include <bits/stdc++.h> using namespace std;
// function performing calculation int max_and( int N, vector< int >& A, int K)
{ // initializing result with 0 .
int result = 0;
for ( int j = 31; j >= 0; j--) {
// initializing temp with (result|(1<<j)) .
int temp = (result | (1 << j));
// initializing count with 0 .
int count = 0;
for ( int j = 0; j < N; j++) {
// counting the number of element having jth bit
// set .
if ((temp & A[j]) == temp) {
count++;
}
}
// checking if there exist K element with jth bit
// set.
if (count >= K) {
// updating result with temp.
result = temp;
}
}
// returning result.
return result;
} // driver function int main()
{ // Given Array A
vector< int > A = { 255, 127, 31, 5, 24, 37 ,15 };
// Size of Array A .
int N = 7;
// Required Subsequence size
int K = 4;
// calling function performing calculation and printing
// the result.
cout
<< "Maximum AND of subsequence of A of size K is : "
<< max_and(N, A, K);
return 0;
} |
import java.util.*;
class Main {
public static int max_and( int N, ArrayList<Integer> A, int K) {
// initializing result with 0 .
int result = 0 ;
for ( int j = 31 ; j >= 0 ; j--) {
// initializing temp with (result|(1<<j)) .
int temp = (result | ( 1 << j));
// initializing count with 0 .
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
// counting the number of element having jth bit
// set .
if ((temp & A.get(i)) == temp) {
count++;
}
}
// checking if there exist K element with jth bit
// set.
if (count >= K) {
// updating result with temp.
result = temp;
}
}
// returning result.
return result;
}
public static void main(String[] args) {
// Given Array A
ArrayList<Integer> A = new ArrayList<Integer>(Arrays.asList( 255 , 127 , 31 , 5 , 24 , 37 , 15 ));
// Size of Array A .
int N = 7 ;
// Required Subsequence size
int K = 4 ;
// calling function performing calculation and printing
// the result.
System.out.println( "Maximum AND of subsequence of A of size K is : " + max_and(N, A, K));
}
} |
# Python program to find the sum of # the addition of all possible subsets. # function performing calculation def max_and(N, A, K):
# initializing result with 0 .
result = 0
for j in range ( 31 , - 1 , - 1 ):
# initializing temp with (result|(1<<j)) .
temp = (result | ( 1 << j))
# initializing count with 0 .
count = 0
for j in range (N):
# counting the number of element having jth bit
# set .
if (temp & A[j]) = = temp:
count = count + 1
# checking if there exist K element with jth bit
# set.
if count > = K:
# updating result with temp.
result = temp
# returning result.
return result
# Given Array A A = [ 255 , 127 , 31 , 5 , 24 , 37 , 15 ]
# Size of Array A . N = 7
# Required Subsequence size K = 4
# calling function performing calculation and printing # the result. print ( "Maximum AND of subsequence of A of size K is : " , max_and(N, A, K))
# The code is contributed by Nidhi goel. |
// Javascript program to find the sum of // the addition of all possible subsets. // function performing calculation function max_and(N, A, K)
{ // initializing result with 0 .
let result = 0;
for (let j = 31; j >= 0; j--)
{
// initializing temp with (result|(1<<j)) .
let temp = (result | (1 << j));
// initializing count with 0 .
let count = 0;
for (let j = 0; j < N; j++)
{
// counting the number of element having jth bit
// set .
if ((temp & A[j]) == temp) {
count = count + 1;
}
}
// checking if there exist K element with jth bit
// set.
if (count >= K)
{
// updating result with temp.
result = temp;
}
}
// returning result.
return result;
} // Given Array A let A = [ 255, 127, 31, 5, 24, 37 ,15 ]; // Size of Array A . let N = 7; // Required Subsequence size let K = 4; // calling function performing calculation and printing // the result. console.log( "Maximum AND of subsequence of A of size K is : " , max_and(N, A, K));
// The code is contributed by Gautam goel. |
// C# program to find the sum of // the addition of all possible subsets. using System;
class GFG
{ // Function to find the maximum '&' value // of K elements in subsequence static int findMaxiumAnd( int []a, int n, int k)
{ // initializing result with 0 .
int result = 0;
for ( int j = 31; j >= 0; j--) {
// initializing temp with (result|(1<<j)) .
int temp = (result | (1 << j));
// initializing count with 0 .
int count = 0;
for ( int i = 0; i < n; i++) {
// counting the number of element having jth bit
// set .
if ((temp & a[i]) == temp) {
count++;
}
}
// checking if there exist K element with jth bit
// set.
if (count >= k) {
// updating result with temp.
result = temp;
}
}
// returning result.
return result;
} // Driver Code public static void Main(String[] args)
{ int []a = { 255, 127, 31, 5, 24, 37, 15 };
int n = a.Length;
int k = 4;
Console.WriteLine(findMaxiumAnd(a, n, k));
} } // This code is contributed by shubhamrajput6156 |
Maximum AND of subsequence of A of size K is : 24
Time Complexity: O(32*N): where N is the size of Array A
Auxiliary Space: O(1)