Find all distinct subset (or subsequence) sums of an array
Last Updated :
23 Jul, 2025
Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small.
Examples:
Input: arr[] = [1, 2]
Output: [0, 1, 2, 3]
Explanation: Four distinct sums can be calculated which are 0, 1, 2 and 3.
- 0 if we do not choose any number.
- 1 if we choose only 1.
- 2 if we choose only 2.
- 3 if we choose 1 and 2.
Input: arr[] = [1, 2, 3]
Output: [0, 1, 2, 3, 4, 5, 6]
Explanation: Seven distinct sums can be calculated which are 0, 1, 2, 3, 4, 5 and 6.
- 0 if we do not choose any number.
- 1 if we choose only 1.
- 2 if we choose only 2.
- 3 if we choose only 3.
- 4 if we choose 1 and 3.
- 5 if we choose 2 and 3.
- 6 if we choose 1, 2 and 3.
Using Recursion – O(2^n) Time and O(n) Space
The naive solution for this problem is to generate all the subsets, store their sums in a hash set and finally return all keys from the hash set. recursively generates all possible subset sums by considering each element twice - once including it in the sum and once excluding it. When index is reached at n store the current sum to hashSet and return.
Mathematically:
- Include the current element (arr[i]) in the subset sum: distSumRec(arr, n, sum + arr[i], i + 1, s)
- Exclude the current element from the subset sum: distSumRec(arr, n, sum, i + 1, s)
C++
// C++ program to print distinct subset sums of
// a given array.
#include<bits/stdc++.h>
using namespace std;
// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
void distSumRec(vector<int> &arr, int n, int sum,
int i, set<int> &s) {
if (i > n)
return;
// If we have considered all elements in the array,
// insert the current sum into the set
if (i == n) {
s.insert(sum);
return;
}
// Include the current element (arr[i]) in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, s);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, s);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return it.
vector<int> DistinctSum(vector<int> &arr) {
// Set to store distinct sums
set<int> s;
int n = arr.size();
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, s);
vector<int> result;
for(int i : s) result.push_back(i);
return result;
}
int main() {
vector<int> arr = {2, 3, 4, 5, 6};
vector<int> result = DistinctSum(arr);
for(int i : result) {
cout << i << " ";
}
return 0;
}
Java
// Java program to print distinct subset sums of a given
// array.
import java.util.*;
class GfG {
// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
static void distSumRec(int[] arr, int n, int sum, int i,
Set<Integer> s) {
if (i > n)
return;
// If we have considered all elements in the array,
// insert the current sum into the set
if (i == n) {
s.add(sum);
return;
}
// Include the current element (arr[i]) in the
// subset sum
distSumRec(arr, n, sum + arr[i], i + 1, s);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, s);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return it.
static List<Integer> DistinctSum(int[] arr) {
// Set to store distinct sums
Set<Integer> s = new HashSet<>();
int n = arr.length;
// Start the recursive process with an initial sum
// of 0 and index 0
distSumRec(arr, n, 0, 0, s);
List<Integer> result = new ArrayList<>(s);
return result;
}
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5, 6 };
List<Integer> result = DistinctSum(arr);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print distinct subset sums of a given array.
# Recursive function to calculate distinct subset sums
# sum: the current sum of the subset
def distSumRec(arr, n, sum, i, s):
if i > n:
return
# If we have considered all elements in the array,
# insert the current sum into the set
if i == n:
s.add(sum)
return
# Include the current element (arr[i])
# in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, s)
# Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, s)
# This function calls distSumRec() to generate
# distinct sum subsets and return it.
def DistinctSum(arr):
# Set to store distinct sums
s = set()
n = len(arr)
# Start the recursive process with an initial
# sum of 0 and index 0
distSumRec(arr, n, 0, 0, s)
return list(s)
arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to print distinct subset sums of a given
// array.
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
static void distSumRec(int[] arr, int n, int sum, int i,
HashSet<int> s) {
if (i > n)
return;
// If we have considered all elements in the array,
// insert the current sum into the set
if (i == n) {
s.Add(sum);
return;
}
// Include the current element (arr[i]) in the
// subset sum
distSumRec(arr, n, sum + arr[i], i + 1, s);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, s);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return it.
static List<int> DistinctSum(int[] arr) {
// Set to store distinct sums
HashSet<int> s = new HashSet<int>();
int n = arr.Length;
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, s);
List<int> result = new List<int>(s);
result.Sort();
return result;
}
static void Main() {
int[] arr = { 2, 3, 4, 5, 6 };
List<int> result = DistinctSum(arr);
foreach(int i in result) { Console.Write(i + " "); }
}
}
JavaScript
// JavaScript program to print distinct subset sums of a
// given array.
// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
function distSumRec(arr, n, sum, i, s) {
if (i > n)
return;
// If we have considered all elements in the array,
// insert the current sum into the set
if (i === n) {
s.add(sum);
return;
}
// Include the current element (arr[i]) in the subset
// sum
distSumRec(arr, n, sum + arr[i], i + 1, s);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, s);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return it.
function DistinctSum(arr) {
// Set to store distinct sums
let s = new Set();
let n = arr.length;
// Start the recursive process with an initial sum of 0
// and index 0
distSumRec(arr, n, 0, 0, s);
return Array.from(s).sort((a, b) => a - b);
}
let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));
Output0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Using Top-Down DP (Memoization) - O(n * sum) Time and O(n * sum) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure: The solution to the Distinct Subset Sum Problem can be derived from the optimal solutions of smaller subproblems.
- Include the current element in the subset: If the current element (arr[i]) is included in the subset, the new required sum becomes sum + arr[i].
- Exclude the current element from the subset: If the current element is excluded, the required sum remains the same.
2. Overlapping Subproblems: In this case, the subproblems overlap because the same subset sums are computed multiple times during recursion. For example, when considering an element in the set, the same sum can be encountered in different recursive calls.
- We create a 2D memoization table memo[n+1][totalSum+1] where n is the number of elements in the array and totalSum is the sum of all the elements in the array. Each entry memo[i][sum] will store whether the sum sum can be formed by the first i elements of the array.
- Initially, all entries are set to -1 to indicate that no subproblems have been computed yet.
- Before computing memo[i][sum], we check if it is already computed by checking if memo[i][sum] != -1. If it's already computed, we return the stored result; otherwise, we calculate it recursively using the inclusion/exclusion approach.
C++
// C++ program to print distinct subset sums of
// a given array.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to calculate distinct subset sums
void distSumRec(vector<int> &arr, int n, int sum,
int i, vector<vector<int>> &memo) {
// If we have considered all elements in
// the array, mark this sum
if (i == n) {
memo[i][sum] = 1;
return;
}
// If this state has already been computed,
// skip further processing
if (memo[i][sum] != -1)
return;
// Mark the current state as visited
memo[i][sum] = 1;
// Include the current element (arr[i]) in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, memo);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, memo);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return them
vector<int> DistinctSum(vector<int> &arr) {
int n = arr.size();
// Calculate the maximum possible sum
int totalSum = accumulate(arr.begin(), arr.end(), 0);
// Memoization table initialized with -1
vector<vector<int>> memo(n + 1, vector<int>(totalSum + 1, -1));
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, memo);
// Collect all distinct sums from the memo table
vector<int> result;
for (int i = 0; i <= totalSum; i++) {
if (memo[n][i] == 1) {
result.push_back(i);
}
}
return result;
}
int main() {
vector<int> arr = {2, 3, 4, 5, 6};
vector<int> result = DistinctSum(arr);
for (int i : result) {
cout << i << " ";
}
return 0;
}
Java
// Java program to print distinct subset sums of
// a given array.
import java.util.*;
class GfG {
// Recursive function to calculate distinct subset sums
static void distSumRec(int[] arr, int n, int sum,
int i, int[][] memo) {
// If we have considered all elements in
// the array, mark this sum
if (i == n) {
memo[i][sum] = 1;
return;
}
// If this state has already been computed,
// skip further processing
if (memo[i][sum] != -1)
return;
// Mark the current state as visited
memo[i][sum] = 1;
// Include the current element (arr[i]) in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, memo);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, memo);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return them
static List<Integer> DistinctSum(int[] arr) {
int n = arr.length;
// Calculate the maximum possible sum
int totalSum = Arrays.stream(arr).sum();
// Memoization table initialized with -1
int[][] memo = new int[n + 1][totalSum + 1];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, memo);
// Collect all distinct sums from the memo table
List<Integer> result = new ArrayList<>();
for (int i = 0; i <= totalSum; i++) {
if (memo[n][i] == 1) {
result.add(i);
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 5, 6};
List<Integer> result = DistinctSum(arr);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print distinct subset sums of
# a given array.
# Recursive function to calculate distinct subset sums
def distSumRec(arr, n, sum, i, memo):
# If we have considered all elements in
# the array, mark this sum
if i == n:
memo[i][sum] = 1
return
# If this state has already been computed,
# skip further processing
if memo[i][sum] != -1:
return
# Mark the current state as visited
memo[i][sum] = 1
# Include the current element (arr[i]) in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, memo)
# Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, memo)
# This function calls distSumRec() to generate
# distinct sum subsets and return them
def DistinctSum(arr):
n = len(arr)
# Calculate the maximum possible sum
totalSum = sum(arr)
# Memoization table initialized with -1
memo = [[-1 for _ in range(totalSum + 1)] for _ in range(n + 1)]
# Start the recursive process with an
# initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, memo)
# Collect all distinct sums from the memo table
result = []
for i in range(totalSum + 1):
if memo[n][i] == 1:
result.append(i)
return result
if __name__ == "__main__":
arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
for i in result:
print(i, end=" ")
C#
// C# program to print distinct subset sums of
// a given array.
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to calculate distinct subset sums
static void distSumRec(int[] arr, int n, int sum,
int i, int[,] memo) {
// If we have considered all elements in
// the array, mark this sum
if (i == n) {
memo[i, sum] = 1;
return;
}
// If this state has already been computed,
// skip further processing
if (memo[i, sum] != -1)
return;
// Mark the current state as visited
memo[i, sum] = 1;
// Include the current element (arr[i])
// in the subset sum
distSumRec(arr, n, sum + arr[i], i + 1, memo);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, memo);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return them
static List<int> DistinctSum(int[] arr) {
int n = arr.Length;
// Calculate the maximum possible sum
int totalSum = 0;
foreach (var num in arr) {
totalSum += num;
}
// Memoization table initialized with -1
int[,] memo = new int[n + 1, totalSum + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= totalSum; j++) {
memo[i, j] = -1;
}
}
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, memo);
// Collect all distinct sums from
// the memo table
List<int> result = new List<int>();
for (int i = 0; i <= totalSum; i++) {
if (memo[n, i] == 1) {
result.Add(i);
}
}
return result;
}
static void Main() {
int[] arr = {2, 3, 4, 5, 6};
List<int> result = DistinctSum(arr);
foreach (int sum in result) {
Console.Write(sum + " ");
}
}
}
JavaScript
// JavaScript program to print distinct subset sums of
// a given array.
// Recursive function to calculate distinct subset sums
function distSumRec(arr, n, sum, i, memo) {
// If we have considered all elements in
// the array, mark this sum
if (i === n) {
memo[i][sum] = 1;
return;
}
// If this state has already been computed,
// skip further processing
if (memo[i][sum] !== -1) {
return;
}
// Mark the current state as visited
memo[i][sum] = 1;
// Include the current element (arr[i]) in the subset
// sum
distSumRec(arr, n, sum + arr[i], i + 1, memo);
// Exclude the current element from the subset sum
distSumRec(arr, n, sum, i + 1, memo);
}
// This function calls distSumRec() to generate
// distinct sum subsets and return them
function DistinctSum(arr) {
const n = arr.length;
// Calculate the maximum possible sum
const totalSum = arr.reduce((acc, num) => acc + num, 0);
// Memoization table initialized with -1
const memo
= Array.from({length : n + 1},
() => Array(totalSum + 1).fill(-1));
// Start the recursive process with an
// initial sum of 0 and index 0
distSumRec(arr, n, 0, 0, memo);
// Collect all distinct sums from the memo table
const result = [];
for (let i = 0; i <= totalSum; i++) {
if (memo[n][i] === 1) {
result.push(i);
}
}
return result;
}
const arr = [ 2, 3, 4, 5, 6 ];
const result = DistinctSum(arr);
console.log(result.join(" "));
Output0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Using Bottom-Up DP (Tabulation) – O(n * sum) Time and O(n * sum) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
We will create a 2D array dp[][] of size (n + 1) x (sum + 1) where sum is the sum of all elements in the array. Each dp[i][j] represents whether a subset of the first i elements of the array can sum to j. dp[i][j] = true means that there is a subset of elements from arr[0..i-1] that sums to j.
Base case:
- We always have a subset with sum 0, which is the empty subset. Therefore, we initialize the first column dp[i][0] = true for all i, as the sum of 0 is always achievable with the empty subset.
For every element arr[i-1], we will either include or exclude it in the subset sum, and update the table accordingly.
- Including the Element: If we include arr[i-1], then the new sum becomes j + arr[i-1]. So, we will check the previous state dp[i-1][j-arr[i-1]] to see if that sum was possible.
- Excluding the Element: If we exclude arr[i-1], then the sum remains j, and we will check the previous state dp[i-1][j] to see if that sum was possible without including the element.
C++
// C++ program to print distinct subset sums of
// a given array.
#include <bits/stdc++.h>
using namespace std;
// Uses Dynamic Programming to find distinct
// subset sums
vector<int> DistinctSum(vector<int> &arr) {
int n = arr.size();
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// dp[i][j] would be true if arr[0..i-1] has
// a subset with sum equal to j.
vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1));
// There is always a subset with 0 sum
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Fill dp[][] in bottom up manner
for (int i = 1; i <= n; i++) {
dp[i][arr[i - 1]] = true;
for (int j = 1; j <= sum; j++) {
// Sums that were achievable
// without current array element
if (dp[i - 1][j] == true) {
dp[i][j] = true;
dp[i][j + arr[i - 1]] = true;
}
}
}
vector<int> result;
for (int j = 0; j <= sum; j++)
if (dp[n][j] == true)
result.push_back(j);
return result;
}
int main() {
vector<int> arr = {2, 3, 4, 5, 6};
vector<int> res = DistinctSum(arr);
for (int i : res)
cout << i << " ";
return 0;
}
Java
// Java program to print distinct subset sums of
// a given array using dynamic programming.
import java.util.*;
class GfG {
// Uses Dynamic Programming to find
// distinct subset sums
static List<Integer> DistinctSum(int[] arr) {
int n = arr.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// dp[i][j] would be true if arr[0..i-1] has a
// subset with sum equal to j.
boolean[][] dp = new boolean[n + 1][sum + 1];
// There is always a subset with 0 sum
for (int i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill dp[][] in bottom up manner
for (int i = 1; i <= n; i++) {
dp[i][arr[i - 1]] = true;
for (int j = 1; j <= sum; j++) {
// Sums that were achievable without the
// current array element
if (dp[i - 1][j] == true) {
dp[i][j] = true;
dp[i][j + arr[i - 1]] = true;
}
}
}
List<Integer> result = new ArrayList<>();
for (int j = 0; j <= sum; j++) {
if (dp[n][j]) {
result.add(j);
}
}
return result;
}
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5, 6 };
List<Integer> result = DistinctSum(arr);
for (int i : result) {
System.out.print(i + " ");
}
}
}
Python
# Python program to print distinct subset sums of
# a given array using dynamic programming.
# Uses Dynamic Programming to find distinct
# subset sums
def DistinctSum(arr):
n = len(arr)
total_sum = sum(arr)
# dp[i][j] would be true if arr[0..i-1] has a
# subset with sum equal to j.
dp = [[False] * (total_sum + 1) for _ in range(n + 1)]
# There is always a subset with 0 sum
for i in range(n + 1):
dp[i][0] = True
# Fill dp[][] in bottom up manner
for i in range(1, n + 1):
dp[i][arr[i - 1]] = True
for j in range(1, total_sum + 1):
# Sums that were achievable without the
# current array element
if dp[i - 1][j]:
dp[i][j] = True
dp[i][j + arr[i - 1]] = True
result = [j for j in range(total_sum + 1) if dp[n][j]]
return result
arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to print distinct subset sums of
// a given array using dynamic programming.
using System;
using System.Collections.Generic;
class GfG {
// Uses Dynamic Programming to find
// distinct subset sums
static List<int> DistinctSum(int[] arr) {
int n = arr.Length;
int sum = 0;
foreach(int num in arr) sum += num;
// dp[i][j] would be true if arr[0..i-1]
// has a subset with sum equal to j.
bool[, ] dp = new bool[n + 1, sum + 1];
// There is always a subset with 0 sum
for (int i = 0; i <= n; i++) {
dp[i, 0] = true;
}
// Fill dp[][] in bottom up manner
for (int i = 1; i <= n; i++) {
dp[i, arr[i - 1]] = true;
for (int j = 1; j <= sum; j++) {
// Sums that were achievable without the
// current array element
if (dp[i - 1, j]) {
dp[i, j] = true;
dp[i, j + arr[i - 1]] = true;
}
}
}
List<int> result = new List<int>();
for (int j = 0; j <= sum; j++) {
if (dp[n, j]) {
result.Add(j);
}
}
return result;
}
static void Main() {
int[] arr = { 2, 3, 4, 5, 6 };
List<int> result = DistinctSum(arr);
foreach(int i in result) { Console.Write(i + " "); }
}
}
JavaScript
// JavaScript program to print distinct subset sums
// of a given array using dynamic programming.
// Uses Dynamic Programming to find distinct subset sums
function DistinctSum(arr) {
const n = arr.length;
const totalSum = arr.reduce((acc, num) => acc + num, 0);
// dp[i][j] would be true if arr[0..i-1] has a
// subset with sum equal to j.
let dp
= Array.from({length : n + 1},
() => Array(totalSum + 1).fill(false));
// There is always a subset with 0 sum
for (let i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill dp[][] in bottom up manner
for (let i = 1; i <= n; i++) {
dp[i][arr[i - 1]] = true;
for (let j = 1; j <= totalSum; j++) {
// Sums that were achievable without the current
// array element
if (dp[i - 1][j]) {
dp[i][j] = true;
dp[i][j + arr[i - 1]] = true;
}
}
}
let result = [];
for (let j = 0; j <= totalSum; j++) {
if (dp[n][j]) {
result.push(j);
}
}
return result;
}
let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));
Output0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Optimized Bit-set Approach:
Above Code snippet does the same as naive solution, where dp is a bit mask (we’ll use bit-set). Lets see how:
- dp ? all the sums which were produced before element a[i]
- dp << a[i] ? shifting all the sums by a[i], i.e. adding a[i] to all the sums.
- For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).
- Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.
- This can be denoted by 010100000 which is equivalent to (000010100) << 3
- dp | (dp << a[i]) ? 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7.
C++
// C++ program to compute all possible
// distinct subset sums using BitSet
#include <bits/stdc++.h>
using namespace std;
// Function to compute all possible
// distinct subset sums using bitset
vector<int> DistinctSum(vector<int> &arr) {
int n = arr.size();
// Calculate total sum of the array
int sum = accumulate(arr.begin(), arr.end(), 0);
// Bitset of size sum+1, dp[i] is 1
// if sum i is possible, 0 otherwise
bitset<100001> dp;
// Sum 0 is always possible (empty subset)
dp[0] = 1;
for (int i = 0; i < n; ++i) {
// Shift the current possible sums by a[i]
dp |= dp << arr[i];
}
// Collect all the sums that are possible
vector<int> res;
for (int i = 0; i <= sum; ++i) {
if (dp[i]) {
// If dp[i] is 1, it means sum i is possible
res.push_back(i);
}
}
return res;
}
int main() {
vector<int> arr = {2, 3, 4, 5, 6};
vector<int> result = DistinctSum(arr);
for (int sum : result) {
cout << sum << " ";
}
return 0;
}
Java
// Java program to compute all possible
// distinct subset sums using BitSet
import java.util.*;
class GfG {
// Function to compute all possible
// distinct subset sums using BitSet
static List<Integer> DistinctSum(int[] arr) {
int n = arr.length;
// Calculate total sum of the array
int sum = Arrays.stream(arr).sum();
// BitSet of size sum+1, dp[i] is 1
// if sum i is possible, 0 otherwise
BitSet dp = new BitSet(sum + 1);
// Sum 0 is always possible (empty subset)
dp.set(0);
for (int i = 0; i < n; ++i) {
// Create a copy of the current dp state
BitSet temp = (BitSet) dp.clone();
// Add the current element to the previously
// possible sums
for (int j = 0; j <= sum; ++j) {
if (dp.get(j)) {
temp.set(j + arr[i]);
}
}
// Update dp with the new sums
dp.or(temp);
}
// Collect all the sums that are possible
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= sum; ++i) {
if (dp.get(i)) {
// If dp[i] is 1, it means sum i is possible
res.add(i);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 5, 6};
List<Integer> result = DistinctSum(arr);
for (int sum : result) {
System.out.print(sum + " ");
}
}
}
Python
# Python program to compute all possible
# distinct subset sums using bitset
# Function to compute all possible
# distinct subset sums using bitset
def DistinctSum(arr):
n = len(arr)
# Calculate total sum of the array
total_sum = sum(arr)
# Bitset of size total_sum+1, dp[i] is 1 if
# sum i is possible, 0 otherwise
dp = [False] * (total_sum + 1)
# Sum 0 is always possible (empty subset)
dp[0] = True
for num in arr:
# Shift the current possible sums by num
for j in range(total_sum, num - 1, -1):
if dp[j - num]:
dp[j] = True
# Collect all the sums that are possible
result = [i for i in range(total_sum + 1) if dp[i]]
return result
arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to compute all possible
// distinct subset sums using BitArray
using System;
using System.Collections;
using System.Collections.Generic;
class GfG {
// Function to compute all possible
// distinct subset sums using BitArray
static List<int> DistinctSum(int[] arr) {
int n = arr.Length;
// Calculate total sum of the array
int sum = 0;
foreach(var num in arr) sum += num;
// BitArray of size sum+1, dp[i] is 1 if
// sum i is possible, 0 otherwise
BitArray dp = new BitArray(sum + 1);
// Sum 0 is always possible (empty subset)
dp[0] = true;
for (int i = 0; i < n; ++i) {
// Create a clone of the current dp state
BitArray temp = (BitArray)dp.Clone();
for (int j = 0; j <= sum - arr[i]; ++j) {
if (dp[j]) {
temp[j + arr[i]] = true;
}
}
// Update dp with the new sums
dp = temp;
}
// Collect all the sums that are possible
List<int> result = new List<int>();
for (int i = 0; i <= sum; ++i) {
if (dp[i]) {
// If dp[i] is true, it means sum i is
// possible
result.Add(i);
}
}
return result;
}
static void Main() {
int[] arr = { 2, 3, 4, 5, 6 };
List<int> result = DistinctSum(arr);
foreach(int sum in result) {
Console.Write(sum + " ");
}
}
}
JavaScript
// JavaScript program to compute all possible
// distinct subset sums using bitset
// Function to compute all possible
// distinct subset sums using bitset
function DistinctSum(arr) {
const n = arr.length;
// Calculate total sum of the array
const totalSum = arr.reduce((acc, num) => acc + num, 0);
// Bitset of size totalSum+1, dp[i] is 1
// if sum i is possible, 0 otherwise
let dp = Array(totalSum + 1).fill(false);
// Sum 0 is always possible (empty subset)
dp[0] = true;
for (let i = 0; i < n; ++i) {
// Shift the current possible sums by a[i]
for (let j = totalSum; j >= arr[i]; --j) {
if (dp[j - arr[i]]) {
dp[j] = true;
}
}
}
// Collect all the sums that are possible
let result = [];
for (let i = 0; i <= totalSum; ++i) {
if (dp[i]) {
result.push(i);
}
}
return result;
}
let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));
Output0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Time Complexity: also seems to be O(n * s). Because if we would have used a array instead of bitset the shifting would have taken linear time O(S). However the shift (and almost all) operation on bitset takes O(s / w) time. Where w is the word size of the system, Usually its 32 bit or 64 bit. Thus the final time complexity becomes O(n * s / w)
Auxiliary Space:O(m), where m is the maximum value of the input array.
Some Important Points:
- The size of bitset must be a constant, this sometimes is a drawback as we might waste some space.
- Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size w = 3.
- Bitset optimized knapsack solution reduced the time complexity by a factor of w which sometimes is just enough to get AC.
Find all distinct subset (or subsequence) sums | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem