Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Subset Sums

Medium Acceptance 72.55% Points 30.00

Given a array arr of integers, return the sums of all subsets in the list. Return the sums in sorted order.

Examples
Example 1

Example 1

Input: arr[] = [1, 3]

Output: [0, 1, 3, 4]

Explanation: The possible subset sums are: 0 (empty subset). 1 (from the element 1). 3 (from the element 3). 4 (from the combination of 1 and 3). These are all the subset sums of the array [1, 3]. The sums are returned in any order.

Example 2

Example 2

Input: arr[] = [2, 5, 7]

Output: [0, 2, 5, 7, 7, 12, 14, 17]

Explanation: The possible subset sums of the array [2, 5, 7] are 0 (from the empty subset), 2 (from the element 2), 5 (from the element 5), 7 (from the element 7), 7 (from the combination of 2 and 5), 12 (from the combination of 2 and 7), 14 (from the combination of 5 and 7), and 17 (from the combination of 2, 5, and 7). These are all the subset sums, which are returned in any order.

Hints
Hint 1
Expected Time Complexity: O(2^n)
Hint 2
Expected Auxiliary Space: O(2^n)
Constraints
  • 1 <= arr.size() <= 15
  • 0 <= arr[i] <= 10^4
Companies
Microsoft Apple Visa Walmart
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions