Back to Practice Dashboard
Python BasicsEasy

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

Easy

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.

Constraints
  • 1 <= len(arr) <= 20
  • -100 <= arr[i] <= 100

Examples

Example 1
Input
arr = [1, 2, 3]
Output
24
Explanation

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.

Example 2
Input
arr = [5, 10]
Output
30
Explanation

Subsets: [], [5], [10], [5,10]. Sums: 0+5+10+15 = 30. Or: (5+10)*2^1 = 15*2 = 30.

Example 3
Input
arr = [4]
Output
4
Explanation

Subsets: [], [4]. Sums: 0 + 4 = 4. Or: 4 * 2^0 = 4.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
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.

Open in Editor