Tutorialspoint
Problem
Solution
Submissions

All Subsets of a Set (Power Set)

Certification: Advanced Level Accuracy: 100% Submissions: 3 Points: 15

Write a Python function that generates all possible subsets (power set) of a given set represented as a list of distinct integers. The solution should not contain duplicate subsets.

Example 1
  • Input: [1, 2, 3]
  • Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
  • Explanation:
    • Step 1: Start with an empty subset.
    • Step 2: For each element in the input set, create new subsets by including and excluding it.
    • Step 3: For element 1, create [] and [1].
    • Step 4: For element 2, create [] and [1] (excluding 2), and [2] and [1, 2] (including 2).
    • Step 5: For element 3, similarly create all combinations with and without 3.
    • Step 6: Return all 2^3 = 8 possible subsets.
Example 2
  • Input: [0]
  • Output: [[], [0]]
  • Explanation:
    • Step 1: Start with an empty subset [].
    • Step 2: Create a new subset by including the element 0: [0].
    • Step 3: Return both subsets: [] (empty set) and [0] (the set itself).
Constraints
  • 0 ≤ len(nums) ≤ 10
  • -10 ≤ nums[i] ≤ 10
  • All the numbers of nums are unique
  • Time Complexity: O(2^n), where n is the length of the input list
  • Space Complexity: O(2^n)
SetRecursionFacebookAccenture
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to generate all subsets
  • For each element, consider two cases: include it or exclude it
  • Alternatively, use bit manipulation to generate all subsets
  • A set with n elements has 2^n subsets
  • You can also use an iterative approach with binary representation

Steps to solve by this approach:

 Step 1: Find the total number of possible subsets using the formula 2^n for n elements.

 Step 2: Generate numbers from 0 to 2^n-1, where each number represents a unique subset.
 Step 3: For each number, use its binary representation to determine whether to include elements.
 Step 4: If the jth bit of binary representation of i is set, include the jth element in the subset.
 Step 5: Collect all generated subsets into the power set.

Submitted Code :