Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Can an array be split into two subsets with equal sums?

Problem: Can an array be split into two subsets with equal sums?
def can_split(a):
    s = sum(a)
    if s % 2: return False
    reach = 1
    for x in a:
        reach |= reach << x
    return bool(reach >> (s // 2) & 1)
print(can_split([1, 5, 11, 5]), can_split([1, 2, 3, 5]), can_split([3, 3, 3, 4, 5]))
What is printed?
  1. A. True False False
  2. B. True False True
  3. C. True True True
  4. D. False False True

Correct answer: B. True False True

Subset-sum to half the total. The integer 'reach' is a bitset: bit k is set if sum k is achievable; shifting by x adds x to every reachable sum. [1, 5, 11, 5] → 11 = 11 = 1 + 5 + 5. [1, 2, 3, 5] has an odd total 11. [3, 3, 3, 4, 5] → 9 = 4 + 5 = 3 + 3 + 3. O(n · S / wordsize) with a bitset, O(n·S) with a boolean table.

More Coding Interview Problems questions

Exams that ask this topic