As per the implementation of finding all possible sub-array from a given array as follows:
public class AllPossibleSubArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3 };
List<List<Integer>> result = new ArrayList<>();
for (int len = 0; len <= arr.length; len++) {
if (len == 0) {
result.add(new ArrayList<>());
} else {
for (int i = 0; i < arr.length - len + 1; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = i; j < i + len; j++) {
temp.add(arr[j]);
}
result.add(temp);
}
}
}
result.forEach(System.out::println);
}
As per my understanding that time complexity would be O(N^3) as there are three FOR loop.
But this problem is nothing but a power set i.e. finding all possible sub set from a given set. From various forum on web, time complexity of power set is 2^N (Binomial expansion) which is not same as O(N^3).
Am i missing some fundamental ?
That's not correct.
The code that you've posted only finds contiguous subarrays, meaning the list of all elements from one index to another index.
The power set, by contrast, would also include discontiguous subsequences, meaning ones that include two elements without including all of the elements between them.
I should also note that there are only O(n2) subarrays, and if you find a different way to represent them, you can find them in O(n2) time rather than O(n3) time as the code that you've posted does. (Specifically, you need a representation that allows you to reuse the shared parts of the lists, rather than having to copy all required elements every time.) By contrast, if you stick with the representation in your code where each list has a distinct copy, finding all subsets would actually require O(n·2n) time, rather than just O(2n) time.