Skip to the solution
MediumDSA14 min read

How do you check if an array can be partitioned into two equal-sum subsets?

109 views

The problem

Question presented to candidate: "Given an array of positive integers, can you split it into two groups whose sums are equal? Every number must go into one of the two groups. Please code it in Python and tell me the time and space cost."

What a strong answer should cover:

  • The reframing: equal halves exist exactly when the total is even and some subset sums to total / 2.
  • The 1-D subset-sum table dp[s] with base case dp[0] = true and transition dp[s] = dp[s] OR dp[s - x].
  • Why the inner loop runs from target down to x (each item used once โ€” 0/1, not unbounded).
  • Complexity O(n ร— S / 2) time and O(S / 2) space, and why that is pseudo-polynomial; brute force is O(2โฟ).
  • Python details: [False] * (target + 1) is safe for a flat row (booleans are immutable), range(target, x - 1, -1) for the downward loop, and the arbitrary-precision int as a bitset (bits |= bits << x).

Clarifying questions expected:

  • Are all numbers positive integers, and how large can n and the values be?
  • Do you need the actual two subsets, or only true / false?

Code / implementation expected: Yes โ€” a short can_partition(nums) in Python with a 1-D boolean list, plus the odd-sum check.

  • dp
  • subset

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

Pythoncan_partition with one valid split
PythonDownward vs upward loop, and brute force vs DP work
PythonBitset version: one shift-and-OR per item

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 126 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How does the Sieve of Eratosthenes work?

Continue