Count partitions with given difference
Pattern: Subsequences and knapsack
Split the array into two groups whose sums differ by d. If the smaller group sums to s2, the larger is total - s2 and (total - s2) - s2 = d, so s2 = (total - d) / 2. Count the subsets with that sum.
The problem
Count the ways to split arr into two subsets S1 and S2 with sum(S1) - sum(S2) = d and sum(S1) ≥ sum(S2). The answer is taken modulo 10⁹ + 7.
Think first
- If you know the total and the difference, what is each group's sum?
- When is there no answer?
- What remains?
Hints
Brute force, and why it fails
Try every split: 2ⁿ.
The key insight
The difference and the total fix both sums, so the problem becomes counting subsets with one target.
Dry run
| target | 7 |
|---|
arr [5, 2, 6, 4], d = 3: total 17, so the smaller group sums to (17 - 3) / 2 = 7.
Step 1 of 2
The plan
if total < d or (total - d) odd: 0
return countSubsets(arr, (total - d) / 2)
Complexity
- Time
O(n × total)- Space
O(total)
Counting subset sums.
Edge cases
- d larger than the total: 0.
- Odd total - d: 0.
- Zeros in the array.
I've built my logic, show the code
Java
class Solution {
public int countPartitions(int[] arr, int d) {
final int MOD = 1_000_000_007;
int total = 0;
for (int x : arr) total += x;
if (total < d || (total - d) % 2 == 1) return 0; // s1 - s2 = d and s1 + s2 = total give s2 = (total - d) / 2
int target = (total - d) / 2;
int[] ways = new int[target + 1]; // count subsets adding up to the smaller part
ways[0] = 1;
for (int x : arr) for (int s = target; s >= x; s--) ways[s] = (ways[s] + ways[s - x]) % MOD;
return ways[target];
}
}C++
class Solution {
public:
int countPartitions(vector<int>& arr, int d) {
const int MOD = 1000000007;
int total = 0;
for (int x : arr) total += x;
if (total < d || (total - d) % 2 == 1) return 0; // s1 - s2 = d and s1 + s2 = total give s2 = (total - d) / 2
int target = (total - d) / 2;
vector<int> ways(target + 1, 0); // count subsets adding up to the smaller part
ways[0] = 1;
for (int x : arr) for (int s = target; s >= x; s--) ways[s] = (ways[s] + ways[s - x]) % MOD;
return ways[target];
}
};Python
class Solution:
def countPartitions(self, arr: list[int], d: int) -> int:
MOD = 1_000_000_007
total = sum(arr)
if total < d or (total - d) % 2:
return 0 # s2 = (total - d) / 2 must be a whole number
target = (total - d) // 2
ways = [1] + [0] * target # count subsets adding up to the smaller part
for x in arr:
for s in range(target, x - 1, -1):
ways[s] = (ways[s] + ways[s - x]) % MOD
return ways[target]Common mistakes
- Mixing up which group is the smaller one.
- Forgetting the parity check.