I have written an algorithm for power set written as P(a). Just learning about time complexities of algorithms (Big-O), so correct me if I am wrong.
Algorithm:
function powerSet(int[] a ){
ArrayList pw = new ArrayList();
pw.add(" ");
for (int i = 1; i <= a.length; i++) //O(n){
ArrayList<String> tmp = new ArrayList<String>();
for (String e : pw)//O(n) {
if(e.equals(" "))
tmp.add(""+a[i-1]) //contanst time;
else
tmp.add(e+a[i-1]) //constant time;
}
pw.addAll(tmp)//O(1);
}
return pw;
}
Is the time complexity of this O(n)*O(n) = O(n^2), or it is an exponential function (c^n where c > 1) like 2^n, because I am enumerating all possible subsets.
The number of times the outer loop runs is
a.length. The number of times the inner loop runs ispw.length, but this increases as the function runs. So you can’t say that they’re bothO(n). Also,pw.addAll(tmp)is not constant-time.Here, the asymptotic time-complexity is the same as the number of times
tmp.add()is called, which is equal to the final size ofpw:O(2^n).