Python BasicsEasy

Sum of all subsets

Detailed guide and Python implementation for the 'Sum of all subsets' problem.

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?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.