Tutorialspoint
Problem
Solution
Submissions

Subsets

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to generate all possible subsets (the power set) of a given integer array. The solution set must not contain duplicate subsets and can be returned in any order. Each subset should contain unique elements from the original array.

Example 1
  • Input: nums = [1,2,3]
  • Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
  • Explanation:
    • Start with empty subset [].
    • Add subsets containing only one element: [1], [2], [3].
    • Add subsets containing two elements: [1,2], [1,3], [2,3].
    • Add subset containing all elements: [1,2,3].
    • Total of 2^3 = 8 subsets generated.
Example 2
  • Input: nums = [0]
  • Output: [[],[0]]
  • Explanation:
    • Start with empty subset [].
    • Add subset containing the single element: [0].
    • Total of 2^1 = 2 subsets generated.
Constraints
  • 1 ≤ nums.length ≤ 10
  • -10 ≤ nums[i] ≤ 10
  • All the numbers of nums are unique
  • The solution set must not contain duplicate subsets
  • Time Complexity: O(n * 2^n)
  • Space Complexity: O(n * 2^n)
ArraysRecursionBacktracking eBaySwiggy
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 backtracking approach to generate all possible combinations
  • For each element, you have two choices: include it or exclude it from the current subset
  • Start with an empty subset and recursively build subsets by adding elements
  • Use an index to track the current position in the array
  • Add the current subset to the result at each recursive call
  • Backtrack by removing the last added element and trying the next possibility

Steps to solve by this approach:

 Step 1: Initialize an empty result array to store all generated subsets.

 Step 2: Create a backtracking function that takes starting index and current subset as parameters.
 Step 3: Add the current subset to the result array at each recursive call.
 Step 4: Iterate through remaining elements starting from the given index.
 Step 5: Include the current element in the subset and recursively call backtrack.
 Step 6: Remove the current element (backtrack) to try the next possibility.
 Step 7: Return the final result containing all possible subsets.

Submitted Code :