![]() |
VOOZH | about |
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 = 0Input: 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:
Below is the Implementation of the above approach:
2
Time Complexity: O(2N)
Auxiliary Space : O(1)