shlogg · Early preview
Prashant Mishra @prashantrmishra

Optimal Approach For Counting Max Or Subsets In O(2n) Time Complexity

Optimal approach for counting max or subsets in O(2n) time complexity using backtracking. Memoization also possible but not optimal.

Problem
BACKTRACKING: OPTIMAL APPROACH:
TC : 

  O(2n)O(2^n)O(2n)
 where n = 16 (given)

class Solution {
    public int countMaxOrSubsets(int[] nums) {
        int max = 0;// maximum bitwise or is the bitwise of the entire array (which is also a subset)
        for(int i = 0;i<nums.length;i++){
            max = max | nums[i];
        }
        return count(max,0,nums,0);
    }
    public int count(int m, int i, int nums[],int val){
        if(i == nums.length){
            return m ==val ? 1:0;
        }
        int take = count(m,i+1,nums,val | nums[i]);
        int dontTake = count(m, i+1,...