Maximum subset with bitwise OR equal to k in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of non-negative integers and an integer k, find the subset of maximum length with bitwise OR equal to k.

Example

If given input array is = [1, 4, 2] and k = 3 then output is:
[1, 2]
The bitwise OR of 1 and 2 equals 3. It is not possible to obtain
a subset of length greater than 2.

Algorithm

Below are the properties of bitwise OR −

0 OR 0 = 0
1 OR 0 = 1
1 OR 1 = 1
  • for all the positions in the binary representation of k with the bit equal to 0, the corresponding position in the binary representations of all the elements in the resulting subset should necessarily be 0

  • On the other hand, for positions in k with the bit equal to 1, there has to be at least one element with a 1 in the corresponding position. Rest of the elements can have either 0 or 1 in that position, it does not matter.

  • Therefore, to obtain the resulting subset, traverse the initial array. While deciding if the element should be in the resulting subset or not, check whether there is any position in the binary representation of k which is 0 and the corresponding position in that element is 1. If there exists such a position, then ignore that element, else include it in the resulting subset.

  • How to determine if there exists a position in the binary representation of k which is 0 and the corresponding position in an element is 1? Simply take bitwise OR of k and that element. If it does not equal to k, then there exists such a position and the element has to be ignored. If their bitwise OR equals to k, then include the current element in the resulting subset.

  • The final step is to determine if there is at least one element with a 1 in a position with 1 in the corresponding position in k.

  • Simply compute the bitwise OR of the resulting subset. If it equals to k, then this is the final answer. Else no subset exists which satisfies the condition

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void getSubSet(int *arr, int n, int k){
   vector<int> v;
   for (int i = 0; i < n; i++) {
      if ((arr[i] | k) == k)
         v.push_back(arr[i]);
   }
   int ans = 0;
   for (int i = 0; i < v.size(); i++) {
      ans |= v[i];
   }
   if (ans != k) {
      cout << "Subset does not exist" << endl;
      return;
   }
   cout << "Result = ";
   for (int i = 0; i < v.size(); i++) {
      cout << v[i] << " ";
   }
   cout << endl;
}
int main(){
   int arr[] = { 1, 4, 2 };
   int k = 3;
   int n = sizeof(arr) / sizeof(arr[0]);
   getSubSet(arr, n, k);
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Result = 1 2
raja
Published on 30-Jan-2020 16:39:06
Advertisements