Python coding

Split into two equal sums

Decide whether the numbers in nums can be divided into two groups with the same total, where every number goes into exactly one group. Return True or False.

nums has 1 to 200 positive integers, each at most 100. Aim for O(n · S) time, where S is the sum of nums.

Besides the tests, one large input (22 numbers, no split) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • can_split([1,5,11,5]) → true
  • can_split([1,2,5]) → false
  • can_split([3,3,2,2,2]) → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

An odd total never splits. Otherwise the question is whether some group sums to exactly half: a 0/1 knapsack over sums.

Hint 2

Keep reach[s]: some group of the numbers seen so far sums to s, starting with reach[0]. For each x, reach[s] becomes true when reach[s - x] is.

Hint 3

Sweep s downward, from half to x. Upward, x feeds on itself: with [1, 2, 5] it reaches 4 as 1 + 1 + 1 + 1.

Solution and why it works
pythonO(n · S), S = sum(nums) · O(S)
def can_split(nums: list[int]) -> bool:
    total = sum(nums)
    if total % 2:
        return False                     # an odd total never halves
    half = total // 2
    reach = [True] + [False] * half      # reach[s]: some group of the numbers so far sums to s
    for x in nums:
        for s in range(half, x - 1, -1): # downward, so x is used at most once
            if reach[s - x]:
                reach[s] = True
    return reach[half]

Two equal groups exist exactly when some group sums to half the total. Whether a sum is reachable with the first i numbers depends only on the first i − 1: use the number or skip it. That is n × S/2 states at O(1) each, against 2ⁿ subsets. Sweep sums downward so each number counts once; an upward sweep reuses it and says yes to [1, 2, 5]. Greedy fails too: dealing the largest number to the lighter group misses 3 + 3 = 2 + 2 + 2.

Related lab: Big-O growth