Search code examples
javarecursionarraylistcollections

Why the ArrayList comes out to be empty in the below code


The questions wants us to return all the subsets of an array in a list.But in the below code why The list lt remains empty after the code is executed? According to me this list lt should have stored all the subsets....

class Solution {
    public void sub(int idx,int[] nums,List<Integer> arr,ArrayList<List<Integer>> lt){
        if(idx>=nums.length){
            lt.add(arr);
            // System.out.println(arr.toString());
            return;
        }
        arr.add(nums[idx]);
        sub(idx+1,nums,arr,lt);
        arr.remove(arr.size()-1);
        sub(idx+1,nums,arr,lt);
    }

    public List<List<Integer>> subsets(int[] nums) {
        List<Integer> arr=new ArrayList<>();
        ArrayList<List<Integer>> lt=new ArrayList<List<Integer>>();
        sub(0,nums,arr,lt);
        return lt;
    }
}

Solution

  • The problem with the code is that it's modifying the same arr list instance throughout the recursion. When it adds the list arr to the list lt, it's actually adding a reference to the same list instance. As a result, when the code modifies arr, it's also modifying the lists stored in lt.

    class Solution {
        public void sub(int idx,int[] nums,List<Integer> arr,ArrayList<List<Integer>> lt){
            if(idx>=nums.length){
                lt.add(new ArrayList<>(arr));
                // System.out.println(arr.toString());
                return;
            }
            arr.add(nums[idx]);
            sub(idx+1,nums,arr,lt);
            arr.remove(arr.size()-1);
            sub(idx+1,nums,arr,lt);
        }
    
        public List<List<Integer>> subsets(int[] nums) {
            List<Integer> arr=new ArrayList<>();
            ArrayList<List<Integer>> lt=new ArrayList<List<Integer>>();
            sub(0,nums,arr,lt);
            return lt;
        }
    }