2

I have two algorithms to compute power set (all subsets) of a set. For example, {1, 2, 3} => power set is {}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}

One algorithm is using iterative solution; i (outer for loop) runs for the nums arrays and j runs for all subsets computed so far and keeps adding ith number to previously computed subsets.

static List<List<Integer>> subsetItr(int[] nums) {
    List<List<Integer>> subsets = new LinkedList<>();
    subsets.add(new LinkedList<>());
    for (int i = 0; i < nums.length; i++) {
        int size = subsets.size();
        for (int j = 0; j < size; j++) {
            List<Integer> current = new LinkedList<>(subsets.get(j));
            current.add(nums[i]);
            subsets.add(current);
        }
    }
    return subsets;
}

So given this, I'd like to make sure that I am analyzing the running time correctly. Let's say n is the size of nums array then the outer for-loop is O(n). Inner for loop grows exponentially doubled the size each i iteration thus the inner loop is O(2^n). The final complexity is O(n*2^n). Is this slower than the below recursive solution which is O(2^n)?

static List<List<Integer>> subsets(int[] nums) {
    List<Integer> current = new LinkedList<>();
    _subsets(nums, 0, current, ret);
    return ret;
}

static void _subsets(int[] nums, int pos, List<Integer> current) {
    if (pos == nums.length) {
        System.out.println(current);
        return;
    }
    current.add(nums[pos]);
    _subsets(nums, pos + 1, current, ret);
    current.remove(current.size() - 1);
    _subsets(nums, pos + 1, current, ret);
}
2
  • Have you tried measuring it? Commented Jul 15, 2017 at 23:27
  • I did .. if I actually run the program then iterative solution takes a lot longer but I'd like to make sure that my run time analysis is correct. It seems like my analysis for iterative solution is incorrect though per the answer below. Commented Jul 16, 2017 at 0:49

1 Answer 1

1

they are the same, both complexity are O(2^n), because the complexity of your first algorithm is O(1+2+2^2+...+2^(n-1))=O(2^n), you can't just view all the complexity of inner loop as the same, you have to calculate each separately and then add them all as I do, hope this post help you!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.