![]() |
VOOZH | about |
Given an integer array arr[], find all the subsets of the array.
Input: arr[] = [1, 2, 3]
Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
Explanation: The subsets of [1, 2, 3] are: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]Input: arr[] = [2, 4]
Output: [[], [2], [2, 4], [4]]
Explanation: The subsets of [2, 4] are: [[], [2], [2, 4], [4]]
Table of Content
Number of Subsets of an array of size n = 2n
Proof: For each element of the array we have 2 choices:
Since, each element has 2 choice to contribute into the subset and we have total n elements, therefore total subsets = 2n
The idea is to explore possible choices one by one recursively. For each element, there two options, either include it into subset or exclude it.
State Space Tree for printing all subsets using Backtracking:
Suppose an array of size 3 having elements [1, 2, 3], the state space tree can be constructed as below:
[1, 2, 3] [1, 2] [1, 3] [1] [2, 3] [2] [3] []
Time Complexity: O(n * 2n), generating all subsets requires 2n recursive calls, and copying each subset of size up to n takes O(n) time.
Auxiliary Space: O(n), recursion stack and temporary subset use at most n space at a time.
This approach is simpler compared to backtracking, as it just requires basic knowledge of bits.
Each element in an array has only two choices: it can either be included or excluded from a subset. We can represent these choices using bits: 0 means excluded, and 1 means included. The i-th bit corresponds to the i-th element of the array.
For an array of size n, there are 2n possible subsets, and each subset can be uniquely represented by the bit representation of numbers from 0 to 2n - 1.
Example: Consider an array [A, B]:
0 → 00 → A excluded, B excluded → []
1 → 01 → A excluded, B included → [B]
2 → 10 → A included, B excluded → [A]
3 → 11 → A included, B included → [A, B]
Illustration:
Suppose given an array of size 3 = [1, 2, 3]. Generate all the subsets using bit manipulation as shown in the image below:
👁 bit-representation-of-subset[] [1] [2] [1, 2] [3] [1, 3] [2, 3] [1, 2, 3]
Time Complexity: O(n * 2n), generating all subsets requires 2n recursive calls, and copying each subset of size up to n takes O(n) time.
Auxiliary Space: O(n), temporary subset at most n space at a time.