Power set problems require a combination of skills like recursion, iteration, and understanding of combinatorics. They test a programmer’s ability to explore all possible combinations of a dataset, manage edge cases like duplicates, and optimize the solution for performance, making them an excellent choice for technical interviews.
Java solution to subsets/power-set FAANG interview questions
Key takeaways:
A subset is any combination of elements from a set, and the power set is the collection of all subsets. For a set with
elements, the power set contains subsets. Subsets are crucial in combinatorics and are used in problems like decision-making, finding combinations, and organizing data.
Bitwise operations are used to generate the power set, determining element inclusion/exclusion through binary representation.
Duplicates are avoided by sorting the array and skipping subsets with repeated elements.
Time complexity is
and space complexity is due to subset generation and storage.
A subset is any combination of elements from a given set, including the empty set and the set itself. The power set is the set of all possible subsets of a given set. For a set with
Decision-making processes (e.g., subset sums, knapsack problems).
Finding combinations and arrangements.
Data organization tasks (e.g., forming groups, partitions).
Subsets-related questions test your problem-solving ability and understanding of recursion, backtracking, and iterative approaches.
Problem statement of subsets/power-set
Write a program to find all possible subsets (the power set) of a given input array nums. The solution should ensure no duplicate subsets, even if the input array contains duplicates.
Example:
Input:
nums = [1, 2, 2, 2]Output:
[[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2], [2], [2, 2], [2, 2, 2]]Explanation: According to the formula mentioned earlier, the total count of subsets is calculated as
However, the output shows only subsets because duplicate subsets are ignored.
Java solution to subsets/power-set
This program generates the power set of a given input array nums using bitwise operations. For a set with
The process involves an outer loop controlled by a variable called counter, which iterates through all integers from 0 to counter determines which elements are included in the current subset. The table below demonstrates how subsets are generated based on the binary values of counter.
Counter (in decimal) | Counter (in binary) | Subset |
0 | 000 | [] |
1 | 001 | [1] |
2 | 010 | [2] |
3 | 011 | [1, 2] |
4 | 100 | [3] |
5 | 101 | [1, 3] |
6 | 110 | [2, 3] |
7 | 111 | [1, 2, 3] |
Let’s look at the following illustration to get a better understanding of the solution:
Step-by-step algorithm:
Here is the step-by-step approach to generate all unique subsets.
Sort the input array:
Sort
numsto handle duplicates effectively.Sorting ensures that duplicates are adjacent, allowing us to skip them easily.
Initialize variables:
Create an empty list
resultto store all subsets.
Iterate through all possible combinations:
Compute the total number of subsets:
subsetCount = 2^nor1 << n( ).bitwise left shift The bitwise left shift operation (<<) shifts the bits of a number to the left by a specified number of positions. Each left shift multiplies the number by 2, effectively doubling its value. For each integer
counterfrom0tosubsetCount - 1:Initialize an empty list
currentSubsetto build the current subset.Set a boolean
isValidtotrueto track if this subset is valid (used for skipping duplicates).Check each bit:
For each bit position
i(from0to n−1):If the i-th bit of
counteris set (counter & (1 << i) != 0):Check for duplicates:
If
nums[i] == nums[i-1]and the i−1-th bit ofcounteris not set, markisValidasfalseand break the loop.
If no duplicates, add
nums[i]tocurrentSubset.
Add valid subsets:
If
isValidis stilltrueafter the loop, addcurrentSubsettoresult.
Return the result:
After processing all
countervalues, return theresultlist containing all subsets.
Check out this course on how to solve problems using bit manipulation: Master Bit Manipulation for Coding Interviews.
Let’s look at the code for the solution we just discussed.
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class PowerSetBitwise {// Function to generate subsets using bitwise operationspublic static List<List<Integer>> subsetsWithDup(int[] nums) {List<List<Integer>> result = new ArrayList<>();Arrays.sort(nums); // Sort the array to handle duplicatesint subsetCount = 1 << nums.length; // Total subsets: 2^nfor (int counter = 0; counter < subsetCount; counter++) {List<Integer> currentSubset = new ArrayList<>();boolean isValid = true;for (int i = 0; i < nums.length; i++) {if ((counter & (1 << i)) != 0) { // Check if i-th bit is set// Skip duplicatesif (i > 0 && nums[i] == nums[i - 1] && (counter & (1 << (i - 1))) == 0) {isValid = false;break;}currentSubset.add(nums[i]);}}if (isValid) {result.add(new ArrayList<>(currentSubset));}}return result;}// Main driver function with test casespublic static void main(String[] args) {// Test casesint[][] testCases = {{1, 2, 1},{0},{1, 1, 1},{1, 2, 3, 4, 5},{}};// Execute each test casefor (int t = 0; t < testCases.length; t++) {System.out.println("Test Case " + (t + 1) + ":");List<List<Integer>> result = subsetsWithDup(testCases[t]);System.out.println("Input: " + Arrays.toString(testCases[t]));System.out.println("Output: " + result);System.out.println("--------------------------------------------------------------------------------------");}}}
Complexity analysis
The time complexity of the given solution is
The space complexity of the solution is currentSubset and the counter use negligible additional space. Thus, the dominant factor in space usage is the storage of subsets, resulting in a total space complexity of
Dreaming of acing your FAANG interview? Success requires more than just practice—it demands mastering proven coding patterns and problem-solving strategies. Check this highly recommended course, “Grokking the Coding Interview Patterns,” designed to turbocharge your preparation and set you on the path to success!
Frequently asked questions
Haven’t found what you were looking for? Contact Us
Why are power set problems considered a good test of algorithmic skills?
How does sorting the input array impact the subsets generation process?
What role does bitwise manipulation play in solving subsets problems?
Why is the subsets problem a common question in FAANG interviews?
Free Resources
- undefined by undefined
- undefined by undefined