Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading