Search code examples
javabit-manipulationsubset

78.LeetCode/Subsets problem - Solution accepted using helper function, but Memory Limit Exceeds otherwise


I was trying to solve LeetCode medium question Subsets [link (https://leetcode.com/problems/subsets/) using Bit manipulation technique.

First I implemented solution as follows :

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        int num=(int)Math.pow(2,nums.length);
        List<List<Integer>> ans = new ArrayList<>();
        for(int i=0;i<num;i++)
        {
          List<Integer> ls = new ArrayList<>();
          int addNum=nums.length-1;
          while(i>0)
          {
            if((i&1)!=0)
            {
               ls.add(nums[addNum]);
            }
            addNum--;
            i=i>>1;
          }
          ans.add(ls);
        }
        return ans;
    }
}

This solution gives Memory Limit Exceeded error upon running.

Upon checking the solutions section, I found a solution implemented by another user exactly same logic as mine, but using a helper function.

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
       List<List<Integer>> ans=new ArrayList<>();
       int num = (int)Math.pow(2,nums.length);
       for(int i=0;i<num;i++)
       {
         List<Integer> ls = helper(i,nums);
         ans.add(ls);
       }
       return ans;
    }
    public List<Integer> helper(int i, int[] nums)
    {
      List<Integer> ls = new ArrayList<>();
      int j=0;
      while(i>0)
      {
         int rem=i&1;
         if(rem==1)
         {
           ls.add(nums[j]);
         }
         j++;
         i=i>>1;
      }
      return ls;
    }
}

This solution gets accepted.

Both the codes are basically doing the same. Can someone help me why the first code gives Memory Limit Exceeded.


Solution

  • The problem was destructively modifying i in the while loop, which effected the increments in the outer for loop.