Finding All Subsets of an Array or String – The Power of Recursion

Understanding Subsets

Given an array or string, the goal is to find all possible subsets (including the empty set). The total number of subsets for a set of size n is 2^n.

Example:

For the array {1,2,3}, the subsets are:

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

Here, n = 3, so total subsets = 2^3 = 8.

The Key Idea: Recursion & Backtracking

Whenever you face a problem like this, think of backtracking. Remember this golden rule:

"Take or Not Take"

(A legendary tip from Striver! I never forget this line.)

At every step, you have two choices:

  1. Take the element → Include it in the subset.

  2. Not take the element → Move forward without including it.

Breaking It Down:

For {1,2,3}, the recursive tree looks like:

  • Start with {} (empty set).

  • Choose 1{1} or skip it {}.

  • From {1}, choose 2{1,2} or skip it {1}.

  • From {1,2}, choose 3{1,2,3} or {1,2}.

  • Similar steps happen for {}{2}, {2,3}, etc.

This recursive approach efficiently explores all subsets.


Try Coding It Yourself!

I won’t give the code here challenge yourself to implement it

Hint: Start with a function like:

void allSubsets(result, temp, mainArray, index) { 
  // Your logic here
}