#[LeetCode] Inner for loop gets infinite loading while Im 100% the logic is correct, anybody ??

1 messages · Page 1 of 1 (latest)

vital gazelle
#

Hello guys! I was doing an assessment and got a problem about subset numbers. for example if I have {1,2,3}, it should be printed as : [[], [1], [2], [1,2], [3],[1,3],[2,3],[1,2,3]] and if {0} it should print [[],[0]]. After spending like an hour stuck like hell with this 😵‍💫 I came up with a function :

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

    public static void main(String[] args) {
        System.out.println(subsets(new int[]{1,2,3}));
    }
}

when I run this code I don't anything ! however when I the result.size() in a variable like int size = result.size(); it works!

polar hollowBOT
#

<@&987246717831381062> please have a look, thanks.

vital gazelle
#

NOTE: I don't want to listen to Ai answers

#

What are your explanations ?

languid sleet
#

Because in each iteration of the loop you're increasing result.size() by adding items to the list, so i < result.size() will always remain true and the loop will never end. By storing the size in a variable before the loop starts you're only using the initial size as the condition.

limber bane
#

i < result.size() this condition is always true as, you are always adding a value to result.

vital gazelle
#

I dnt understand

#

If i put it in a variable it's also getting filled with items

languid sleet
#

You're only putting the size into a variable, which just creates a copy of that number/value into the new variable. Adding items to the list won't magically change the other variables value since they have no connection.

vital gazelle
#

Huh

languid sleet
#

.size just returns a number which is the list's size at the time of calling the method

vital gazelle
#

That's right

languid sleet
#

So when you call .size and set that value to a variable, if .size returns 2 that variable will now have the value 2. The issue is that you're currently using .size in the loop's condition, which always asks for the new size of the list and since you're always adding items to the list, the size keeps growing which means .size returns a larger value every time

vital gazelle
#

I was dumb i did not notice this

#

Thank you for this analyze