May 4, 2022

Question 40 : Find all subsets of set (power set) in java.

Given a set of distinct integers, arr, return all possible subsets (the power set).

For example :

Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
1

Using recursion

You can find all subsets of set or power set using recursion. Here is the simple approach.

  • As each recursion call will represent subset here, we will add resultList(see recursion code below) to the list of subsets in each call.
  • Iterate over elements of a set.
  • In each iteration
    • Add elements to the list
    • explore(recursion) and make start = i+1 to go through remaining elements of the array.
    • Remove element from the list.

Here is java code for recursion.

import java.util.ArrayList; import java.util.List; public class SubsetsOfSetJava { public static void main(String[] args) { SubsetsOfSetJava soa= new SubsetsOfSetJava(); int[] nums= {1, 2, 1}; List<List<Integer>> subsets = soa.subsets(nums); for (List<Integer> subset: subsets) { System.out.println(subset); } } public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> list = new ArrayList<>(); subsetsHelper(list, new ArrayList<>(), nums, 0); return list; } private void subsetsHelper(List<List<Integer>> list , List<Integer> resultList, int [] nums, int start){ list.add(new ArrayList<>(resultList)); for(int i = start; i < nums.length; i++){ // add element resultList.add(nums[i]); // Explore subsetsHelper(list, resultList, nums, i + 1); // remove resultList.remove(resultList.size() - 1); } } }

Output

[] [1] [1, 2] [1, 2, 1] [1, 1] [2] [2, 1] [1]

Let’s understand with the help of a diagram.


If you notice, each node(resultList) represent subset here.

Using bit manipulation

You can find all subsets of set or power set using iteration as well.

There will be 2^N subsets for a given set, where N is the number of elements in set.
For example, there will be 2^4 = 16 subsets for the set {1, 2, 3, 4}.

Each ‘1’ in the binary representation indicate an element in that position.
For example, the binary representation of number 6 is 0101 which in turn represents the subset {1, 3} of the set {1, 2, 3, 4}.




How can we find out which bit is set for binary representation, so that we can include the element in the subset?

To check if 0th bit is set, you can do logical & with 1 To check if 1st bit is set, you can do logical & with 2 To check if 2nd bit is set, you can do logical & with 2^2 . . To check if nth bit is set, you can do logical & with 2^n.

Let’s say with the help of example:

For a set {1 ,2, 3}

0 1 1  &  0 0 1 = 1    –> 1 will be included in subset

0 1 1  &  0 1 0 = 1    –> 2 will be included in subset

0 1 1  &  1 0  0 =0   –> 3 will not be included in subset.

Here is java code for the bit approach.

public class SubsetBitMain { // Print all subsets of given set[] static void printSubsets(int set[]) { int n = set.length; // Run a loop from 0 to 2^n for (int i = 0; i < (1<<n); i++) { System.out.print("{ "); int m = 1; // m is used to check set bit in binary representation. // Print current subset for (int j = 0; j < n; j++) { if ((i & m) > 0) { System.out.print(set[j] + " "); } m = m << 1; } System.out.println("}"); } } // Driver code public static void main(String[] args) { int set[] = {1 ,2, 3}; printSubsets(set); } }

Output

{ } { 1 } { 2 } { 1 2 } { 3 } { 1 3 } { 2 3 } { 1 2 3 }

Here is a complete representation of the bit manipulation approach.


Backtracking (Standard Recursive)

Idea

At each element, we have 2 choices:

✔ Include the element
✔ Exclude the element

This generates all 2^n subsets.


Java — Recursive Backtracking

import java.util.*; public class AllSubsets { public static List<List<Integer>> subsets(int[] arr) { List<List<Integer>> result = new ArrayList<>(); backtrack(0, arr, new ArrayList<>(), result); return result; } private static void backtrack(int index, int[] arr, List<Integer> current, List<List<Integer>> result) { if (index == arr.length) { result.add(new ArrayList<>(current)); return; } // Exclude backtrack(index + 1, arr, current, result); // Include current.add(arr[index]); backtrack(index + 1, arr, current, result); // backtrack current.remove(current.size() - 1); } }

✔ Time: O(2ⁿ × n)
✔ Space: O(2ⁿ) (result size)


Python — Backtracking

def subsets(arr): result = [] def backtrack(i, current): if i == len(arr): result.append(current.copy()) return # Exclude backtrack(i + 1, current) # Include current.append(arr[i]) backtrack(i + 1, current) current.pop() backtrack(0, []) return result print(subsets([1,2,3]))

Bitmasking (Iterative)

Idea

Each number from 0 to 2^n - 1 represents a subset:

  • Binary digit bit = include/exclude


Java — Bitmasking

import java.util.*; public class SubsetsBitmask { public static List<List<Integer>> subsets(int[] arr) { int n = arr.length; List<List<Integer>> result = new ArrayList<>(); for (int mask = 0; mask < (1 << n); mask++) { List<Integer> subset = new ArrayList<>(); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { subset.add(arr[i]); } } result.add(subset); } return result; } }

Python — Bitmasking

def subsets_bitmask(arr): n = len(arr) result = [] for mask in range(1 << n): subset = [] for i in range(n): if mask & (1 << i): subset.append(arr[i]) result.append(subset) return result

✔ Time: O(2ⁿ × n)
✔ Space: O(2ⁿ)


Iterative Build

Idea

Start with empty set [], then for each element append it to existing subsets.


Java — Iterative

import java.util.*; public class SubsetsIterative { public static List<List<Integer>> subsets(int[] arr) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); for (int num : arr) { int size = result.size(); for (int i = 0; i < size; i++) { List<Integer> subset = new ArrayList<>(result.get(i)); subset.add(num); result.add(subset); } } return result; } }

Python — Iterative

def subsets_iterative(arr): result = [[]] for num in arr: result += [curr + [num] for curr in result] return result
Approach Time Complexity Space Complexity Best Use
Backtracking (recursive) O(2ⁿ × n) O(2ⁿ) ⭐ Standard & versatile
Bitmasking O(2ⁿ × n) O(2ⁿ) ✔ Clean iterative
Iterative build O(2ⁿ × n) O(2ⁿ) ✔ Simple iterative addition

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS