← Back to All Patterns

Subsets Pattern

🎲 Subsets Pattern - Generating Power Set [1, 2, 3]

All Subsets (1 total):

[]

Process:

Size: 1
Add element ?
Size: 1

Step 1: Start with empty set

Progress: 1 / 4

Speed:

Key Formula:

For n elements, there are 2^n subsets. Each element either included or excluded. This BFS approach: start with [], then for each number, add it to all existing subsets!

🎯 Explain Like I'm 5...

Imagine you have 3 toys: Car, Bear, and Crayons. How many different ways can you play? You could play with NONE, or ANY combination!

🎮 All Your Choices (Subsets):

  • Play with NOTHING [] (that's boring!) 😴
  • Just Car [🚗]
  • Just Bear [🧸]
  • Just Crayons [🎨]
  • Car + Bear [🚗, 🧸]
  • Car + Crayons [🚗, 🎨]
  • Bear + Crayons [🧸, 🎨]
  • ALL THREE! [🚗, 🧸, 🎨]

Total: 8 ways! (2 × 2 × 2 = 2³ = 8)

🚀 The Pattern: For EACH toy, you have 2 choices: Include it or Don't include it! With 3 toys, that's 2×2×2 = 8 subsets. It's like a tree where every branch splits into "yes" or "no"! 🌳

When Should You Use This Pattern?

  • Finding all combinations or permutations
  • Problems asking for "all possible" solutions
  • Generating power sets
  • When you need to explore all options

📝 Example 1: Generate All Subsets

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

Step-by-Step Thinking:

  1. Start with empty subset: [[]]
  2. For each number, add it to all existing subsets
  3. Add 1: [[], [1]]
  4. Add 2: [[], [1], [2], [1,2]]
  5. Add 3: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
Subsets.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.*;
public class Subsets {
// Generate all subsets (BFS approach)
public static List<List<Integer>> findSubsets(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
subsets.add(new ArrayList<>()); // Start with empty subset
for (int num : nums) {
// Take all existing subsets and add current number to them
int size = subsets.size();
for (int i = 0; i < size; i++) {
// Create new subset from existing one
List<Integer> newSubset = new ArrayList<>(subsets.get(i));
newSubset.add(num);
subsets.add(newSubset);
}
}
return subsets;
}
// Alternative: Recursive (DFS) approach
public static List<List<Integer>> findSubsetsRecursive(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
backtrack(nums, 0, new ArrayList<>(), subsets);
return subsets;
}
private static void backtrack(int[] nums, int start,
List<Integer> current,
List<List<Integer>> subsets) {
// Add current subset
subsets.add(new ArrayList<>(current));
// Try adding each remaining number
for (int i = start; i < nums.length; i++) {
current.add(nums[i]); // Choose
backtrack(nums, i + 1, current, subsets); // Explore
current.remove(current.size() - 1); // Unchoose (backtrack)
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println("BFS approach:");
System.out.println(findSubsets(nums));
System.out.println("\nDFS approach:");
System.out.println(findSubsetsRecursive(nums));
// Both output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
}
}

📝 Example 2: Subsets with Duplicates

Given an array that may contain duplicates, generate all unique subsets.

SubsetsWithDuplicates.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;
public class SubsetsWithDuplicates {
public static List<List<Integer>> findSubsets(int[] nums) {
// Sort to handle duplicates
Arrays.sort(nums);
List<List<Integer>> subsets = new ArrayList<>();
subsets.add(new ArrayList<>());
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < nums.length; i++) {
startIndex = 0;
// If current element is duplicate, only add to subsets
// created in previous iteration
if (i > 0 && nums[i] == nums[i - 1]) {
startIndex = endIndex + 1;
}
endIndex = subsets.size() - 1;
// Add current number to existing subsets
for (int j = startIndex; j <= endIndex; j++) {
List<Integer> newSubset = new ArrayList<>(subsets.get(j));
newSubset.add(nums[i]);
subsets.add(newSubset);
}
}
return subsets;
}
public static void main(String[] args) {
int[] nums = {1, 2, 2};
List<List<Integer>> subsets = findSubsets(nums);
System.out.println("Subsets: " + subsets);
// Output: [[], [1], [2], [1,2], [2,2], [1,2,2]]
// Note: No duplicate [2] subsets!
}
}

📝 Example 3: Permutations

Generate all permutations of a given array (order matters!).

Permutations.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
public class Permutations {
public static List<List<Integer>> findPermutations(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Queue<List<Integer>> permutations = new LinkedList<>();
permutations.add(new ArrayList<>());
// Process each number
for (int num : nums) {
int n = permutations.size();
// Take each existing permutation
for (int i = 0; i < n; i++) {
List<Integer> oldPermutation = permutations.poll();
// Insert current number at every possible position
for (int j = 0; j <= oldPermutation.size(); j++) {
List<Integer> newPermutation = new ArrayList<>(oldPermutation);
newPermutation.add(j, num);
// If permutation is complete, add to result
if (newPermutation.size() == nums.length) {
result.add(newPermutation);
} else {
permutations.add(newPermutation);
}
}
}
}
return result;
}
// Alternative: Recursive approach with backtracking
public static List<List<Integer>> findPermutationsRecursive(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] nums, List<Integer> current,
List<List<Integer>> result) {
// Base case: permutation is complete
if (current.size() == nums.length) {
result.add(new ArrayList<>(current));
return;
}
// Try adding each number that's not already in current permutation
for (int num : nums) {
if (current.contains(num)) continue; // Skip if already used
current.add(num); // Choose
backtrack(nums, current, result); // Explore
current.remove(current.size() - 1); // Unchoose
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println("Permutations:");
System.out.println(findPermutations(nums));
// Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
}
}

🔑 Key Points to Remember

  • 1️⃣Two approaches: BFS (iterative) or DFS (recursive backtracking)
  • 2️⃣Subsets: 2^n combinations, Permutations: n! orderings
  • 3️⃣Time Complexity: O(2^n) for subsets, O(n!) for permutations
  • 4️⃣For duplicates, sort first and handle carefully!

💪 Practice Problems

  • Letter Case Permutation
  • Combination Sum
  • Palindrome Partitioning
  • Generate Balanced Parentheses
  • Unique Generalized Abbreviations