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 casedp[0] = trueand transitiondp[s] = dp[s] OR dp[s - x]. - Why the inner loop runs from
targetdown tox(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-precisionintas 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.