Imagine you have a set of weights and want to split them into two groups so that the difference in their total weights is as small as possible. This helps in balancing loads or dividing tasks evenly.
Given an array of positive integers, partition the array into two subsets such that the absolute difference between the sums of the subsets is minimized. Return this minimum difference.
1 ≤ n ≤ 1001 ≤ arr[i] ≤ 1000
Edge cases: Single element array → difference equals that elementAll elements equal → difference is 0 if even count, else element valueArray with one very large element and small others → difference close to large element
def min_subset_sum_diff(arr: list[int]) -> int:public int minSubsetSumDiff(int[] arr)int minSubsetSumDiff(vector<int> &arr)function minSubsetSumDiff(arr)
def min_subset_sum_diff(arr):
# Write your solution here
pass
class Solution {
public int minSubsetSumDiff(int[] arr) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int minSubsetSumDiff(vector<int> &arr) {
// Write your solution here
return 0;
}
function minSubsetSumDiff(arr) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 0Greedy approach incorrectly assumes perfect partition possible.✅ Replace greedy logic with DP subset sum approach to find closest sum to half total sum.
Wrong: 0Unbounded knapsack logic allowing multiple uses of same element.✅ Enforce 0/1 knapsack constraint by indexing items and not reusing them in DP.
Wrong: Wrong minimal difference (e.g., 0 or 1 instead of 2)Off-by-one error in DP indexing or boundary conditions.✅ Carefully check DP table indices and transitions to cover all subsets correctly.
Wrong: Non-zero for empty arrayMissing base case for empty input.✅ Add base case to return 0 if input array is empty.
Wrong: Wrong value for single element arrayNot handling single element base case properly.✅ Return the single element value if array length is 1.