VOOZH about

URL: https://www.geeksforgeeks.org/dsa/backtracking-to-find-all-subsets/

⇱ Subsets of a given Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subsets of a given Array

Last Updated : 22 Mar, 2026

Given an integer array arr[], find all the subsets of the array.

  • A subset is any selection from an array, where the order does not matter, and no element appears more than once.
  • A subset can include any number of elements, from none (the empty subset) to all.

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]]

Number of Subsets of an array of size n = 2n

Proof: For each element of the array we have 2 choices:

  • Choice 1: Include it into the subset.
  • Choice 2: Exclude it from the subset.

Since, each element has 2 choice to contribute into the subset and we have total n elements, therefore total subsets = 2n

Using Recursion

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:

👁 frame_3136-

Output
[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.

Using Bit Manipulation

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

Output
[]
[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.

Comment
Article Tags: