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

Subset Leetcode, size of a List

I am really curios about one thing when compiling, in the given code below, where I am creating nested for loop, I am giving as a limit

subsetArr.size()

but when compiling it is saying memory exceeded, and if I define size just before the for loop

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

int size = subsetArr.size()

and then passing limit as size

i<size;

it is working fine. What can be the cause?

class Solution {
   public List<List<Integer>> subsets(int[] nums) {
    
    List<List<Integer>> subsetArr = new ArrayList<>();
    subsetArr.add(new ArrayList());
    
    for(int num: nums){ 
        for(int i=0; i<subsetArr.size(); i++){
            List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
            takenList.add(num);
            subsetArr.add(takenList);
        }
    }
    
    return subsetArr;
}
}

>Solution :

Look at what this loop does:

for(int i=0; i<subsetArr.size(); i++){
    List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
    takenList.add(num);
    subsetArr.add(takenList); // <-- here
}

Each iteration adds to the collection. So in the next iteration, subsetArr.size() will be larger. Thus you have a loop which indefinitely increases the size of the collection until it runs out of resources.

Contrast that to when you store the value:

int size = subsetArr.size();

In this case, while subsetArr.size() may change, size won’t unless you update it. So as long as you don’t update size then you have a finite loop.

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