700360. Sum of subset differences

Medium

Here is a detailed Markdown blog post for the problem:

Sum of subset differences

Summary

This problem involves calculating the sum of all possible differences between subsets of an array. The key concepts involved are arrays and data structures, making it a medium-level difficulty problem.

Detailed Explanation

The problem statement can be interpreted as follows: given an array arr of size n, calculate the sum of all possible differences between non-empty subsets of arr. A subset is a set of distinct elements that can be selected from the original array. The goal is to find the total sum of all possible differences between these subsets.

To solve this problem, we can start by generating all possible subsets of the given array. This can be done using recursion or an iterative approach with bit manipulation. Once we have generated all subsets, we calculate the difference between each pair of subsets and add it to our running total.

Here is a step-by-step breakdown of the solution:

  1. Generate all possible subsets of the input array arr.
  2. For each pair of distinct subsets, calculate their absolute difference.
  3. Add the calculated differences to our running total.
  4. Return the final sum as the result.

Time complexity: O(2^n * n), where n is the size of the input array. This is because we generate all possible subsets and then calculate the differences between each pair, resulting in exponential time complexity.

Space complexity: O(n), where n is the size of the input array. This is because we need to store the generated subsets, which can be as large as the original array.

Optimized Solutions

Java

View on GeeksforGeeks
public int sumOfSubsetDifferences(int[] arr) {
    int n = arr.length;
    int totalSum = 0;

    for (int i = 0; i < (1 << n); i++) {
        int subsetSum = 0;
        for (int j = 0; j < n; j++) {
            if (((i >> j) & 1) == 1) {
                subsetSum += arr[j];
            }
        }
        totalSum += Math.abs(subsetSum);
    }

    return totalSum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.