VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-sums-subsets-given-set/

⇱ Print sums of all subsets of a given set - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print sums of all subsets of a given set

Last Updated : 27 Feb, 2025

Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order.

Examples :

Input: arr[] = {2, 3}
Output: 0 2 3 5
Explanation: All subsets of this array are - {{}, {2}, {3}, {2, 3}}, having sums - 0, 2, 3 and 5 respectively.

Input: arr[] = {2, 4, 5}
Output: 0 2 4 5 6 7 9 11

[Naive Approach] Using Iterative Method - O(N * 2^N) Time and O(1) Space

There are total 2n subsets. The idea is to generate a loop from 0 to 2n - 1. For every number, pick all array elements corresponding to 1s in the binary representation of the current number.

Output :

0 5 4 9 3 8 7 12 

[Expected Approach] Using Recursion - O(2^N) Time and O(N) Space

We can recursively solve this problem. There are total 2n subsets. For every element, we consider two choices, we include it in a subset and we don't include it in a subset. Below is recursive solution based on this idea.

Output :

12 9 8 5 7 4 3 0

[Alternate Approach] Using Iterative method - O(2^N) Time and O(N) Space

In this method, while visiting a new element, we take its sum with all previously stored sums. This method stores the sums of all subsets and hence it is valid for smaller inputs.

Output:

0 5 4 9 3 8 7 12 

The above-mentioned techniques can be used to perform various operations on sub-sets like multiplication, division, XOR, OR, etc, without actually creating and storing the sub-sets and thus making the program memory efficient. 


Comment
Article Tags:
Article Tags: