Number of ways to partition an array into subsets with equal sum?
Short answer: public int CountPartitions(int[] nums) { int sum = 0; foreach (int num in nums) sum += num; if (sum % 2 != 0) return 0; int target = sum / 2; int[] dp = new int[target + 1]; dp[0] = 1; Follow on: foreach (int num in nums) { for (int j = target; j >= num; j--) { dp[j] += dp[j - num]; } } return dp[target]; } Explanation: Classic subset sum DP. dp[j] = ways to get sum j. Counting subsets summing to half the total.
Example code
public int CountPartitions(int[] nums) {
int sum = 0;
foreach (int num in nums) sum += num;
if (sum % 2 != 0) return 0;
int target = sum / 2;
int[] dp = new int[target + 1];
dp[0] = 1; Follow on: foreach (int num in nums) {
for (int j = target; j >= num; j--) {
dp[j] += dp[j - num];
}
}
return dp[target];
} Explanation: Classic subset sum DP. dp[j] = ways to get sum j. Counting subsets summing to half the total.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png