Partition Equal Subset Sum (Bitset Variant)

The same problem as Batch 1 — this duplicate row in the curriculum gets a bitset-accelerated take.

Medium
Time O(n * S / 64) Space O(S / 64)
LeetCode
4 min read
dp knapsack bitset

Problem#

(Same as Partition Equal Subset Sum. The CSV lists this problem twice under Week 13 — the duplicate gets a faster bitset implementation.)

Return true iff nums can be split into two equal-sum subsets.

Examples#

  • [1,5,11,5]true

Constraints#

  • 1 <= n <= 200, sum ≤ 20000.

Approach#

Same DP, but represent the entire dp row as a single bitset<10001>. Each item-update becomes a single dp |= dp << x — 64× faster on average than scalar update.

Solution#

Partition Equal Subset Sum (bitset)
class Solution {
public:
bool canPartition(vector<int>& nums) {
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % 2) return false;
int target = total / 2;
bitset<10001> dp;
dp[0] = 1;
for (int x : nums) dp |= (dp << x);
return dp[target];
}
};

Editorial#

Bitsets compress the boolean state of “reachable sums” into 64-bit chunks. The shift-and-or trick performs all “include this item” transitions in parallel. Same correctness as the scalar 0/1 knapsack — speed is the only difference.

Complexity#

  • Time: O(n * S / 64).
  • Space: O(S / 64).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.