We are required to create all subsets in a given array including an empty subset. This is a classic backtracking use case. Backtracking is an algorithm where you try out all possibilities.
Since the time complexity for backtracking problems is quite inefficient , you would notice that the input size they provide you in leetcode is pretty small.
The idea is that you go till a possible solution and then “backtrack” you way back to a starting point and then start down a different path. Notice the for loop in the below solution? That loop is the secret for this: it helps generate indices sequentially.
Note: this problem can also be solved without using the
visited
boolean array to keep track of indices we have visited. I have included to maintain symmetry since a lot of graph problems use the technique. Since, for every backtracking function call, we start ourfor
loop with acur
index, and not from the start, the visited array is not required. If thecur
index was absent, the visited array was crucial else it would result in a stackoverflow error.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since we try out all possibilites.
-
Memory
The memory usage is since we use the visited array (optional) and the result array. If you don’t take the result array into consideration, this could be a constant memory problem.
— A