Open In App

Split Array into maximum Subsets with same bitwise AND

Last Updated : 29 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N, the task is to find the maximum number of subsets the array can be split such that the bitwise AND of the subsets is the same.

Examples:

Input: N = 4, arr[] = {1, 5, 2, 8}
Output: 2
Explanation:
1st subset -> {1, 8}; bitwise AND = 0 
2nd subset -> {2, 5}; bitwise AND = 0 

Input: N = 3, arr[] = {1, 5, 7}
Output: 1
Explanation: There is no way to split the array into subsets. So all the elements can be considered as a single subset.

Input: N = 5, arr[] = {7, 14, 6, 15, 22}
Output: 3
Explanation: The subsets are {22, 15}, {6} and {7, 14}

Approach: Brute force

Say all the subsets have an equal AND and that is denoted by the variable target. We can find this target value by taking AND of all the elements in the array. This can be proved as follows:

Let's say the subsets are S1, S2, . . ., Sk, and the bitwise AND of each subset is X. So, S1 & S2 & . . . & Sk = target. As all the elements are part of any one subset, so the bitwise AND of all the elements is also a target.

So the task is to find all the possible combinations of elements to find a maximum number of subsets that can be formed.

Follow the steps mentioned below to implement the idea:

  • We can maintain a mask that represents elements taken till now.
  • If the current element is not present in the mask AND it with the mask and there are 2 options for the element:
    • If after adding the element, AND of the subset is not equal to the target, add this element into the current subset.
    • If after adding element strength, AND of the subset is equal to the target then there can be two possible ways:
      • Add this element to the current subset and start adding elements in a new subset.
      • Keep on adding new elements to the current subset.
  • After adding the current element call the function for adding new elements and decrease the value of n by 1.
  • When n becomes zero, check whether all the subsets have AND equal to the target and then update the answer.
  • Check whether all pairs have equal AND by maintaining a 'current' variable that represents the current AND of elements added in a new subset.
    • If the current has all bits set this means, we have found a pair with AND= target [Because n will be 0 when all elements are used and while calling for a new group the initial AND value passed is the same as the default value stored at the starting].
    • Otherwise, the current subset AND is not equal to AND.

Below is the Implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
2

Time Complexity: O(2N)
Auxiliary Space : O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads