# Finding all subsets of a given set in Java

• Difficulty Level : Medium
• Last Updated : 30 Jun, 2022

Problem: Find all the subsets of a given set.

```Input:
S = {a, b, c, d}
Output:
{}, {a} , {b}, {c}, {d}, {a,b}, {a,c},
{a,d}, {b,c}, {b,d}, {c,d}, {a,b,c},
{a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d}```

The total number of subsets of any given set is equal to 2^ (no. of elements in the set). If we carefully notice it is nothing but binary numbers from 0 to 15 which can be shown as below:

Starting from right, 1 at ith position shows that the ith element of the set is present as 0 shows that the element is absent. Therefore, what we have to do is just generate the binary numbers from 0 to 2^n – 1, where n is the length of the set or the numbers of elements in the set.

Implementation:

## Java

 `// A Java program to print all subsets of a set``import` `java.io.IOException;` `class` `Main``{``    ``// Print all subsets of given set[]``    ``static` `void` `printSubsets(``char` `set[])``    ``{``        ``int` `n = set.length;` `        ``// Run a loop for printing all 2^n``        ``// subsets one by one``        ``for` `(``int` `i = ``0``; i < (``1``< ``0``)``                    ``System.out.print(set[j] + ``" "``);` `            ``System.out.println(``"}"``);``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``char` `set[] = {``'a'``, ``'b'``, ``'c'``};``        ``printSubsets(set);``    ``}``}`

Output

```{ }
{ a }
{ b }
{ a b }
{ c }
{ a c }
{ b c }
{ a b c }```

Time complexity: O(n * (2^n)) as the outer loop runs for O(2^n) and the inner loop runs for O(n).

Related Post:
Finding all subsets of a Set in C/C++

This article is contributed by Nikhil Tekwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up