Size of the smallest subset with maximum Bitwise OR

Given an array of positive integers. The task is to find the size of the smallest subset such that the Bitwise OR of that set is Maximum possible.

Examples:

Input : arr[] = {5, 1, 3, 4, 2}
Output : 2
7 is the maximum value possible of OR, 
5|2 = 7 and 5|3 = 7

Input : arr[] = {2, 6, 2, 8, 4, 5}
Output : 3
15 is the maximum value of OR and set
elements are 8, 6, 5

Source :Sprinklr on Campus Internship

Doing bitwise OR of a number with some value does not decrease its value. It either keeps the value same or increases. If we take a closer look at the problem we can notice that the maximum OR value that we can get is by doing bitwise OR of all array elements. But this includes all elements and here want to know the smallest subset. So we do the following.

I) Find bitwise OR of all array elements. This is the OR we are looking for.
II) Now we need to find the smallest subset with this bitwise OR. This problem is similar to subset sum provblem, We can solve it two ways :

  1. We recursively generate all subsets and return the smallest size with given OR
  2. We use Dynamic Programming to solve the problem. This solution is going to be very similar to Maximum size subset with given sum

The time complexity of the recursive solution is O(2^n) and time complexity of the Dynamic Programming solution is O(OR * n) where OR is OR of all array elements and n is size of input array.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.