Sum of all subsets
Learn how to solve the 'Sum of all subsets' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function sum_of_all_subsets(arr) that takes an array of integers and returns the total sum of all elements across all possible subsets. For an array of n elements, each element appears in exactly 2^(n-1) subsets. So the total sum equals sum(arr) * 2^(n-1). Use recursion to compute this.
- •1 <= len(arr) <= 20
- •-100 <= arr[i] <= 100
Examples
arr = [1, 2, 3]
24
Subsets: [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]. Sums: 0+1+2+3+3+4+5+6 = 24. Or: (1+2+3)*2^(3-1) = 6*4 = 24.
arr = [5, 10]
30
Subsets: [], [5], [10], [5,10]. Sums: 0+5+10+15 = 30. Or: (5+10)*2^1 = 15*2 = 30.
arr = [4]
4
Subsets: [], [4]. Sums: 0 + 4 = 4. Or: 4 * 2^0 = 4.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.