Python coding

Deal numbers into k equal piles

Given a list nums of positive integers and an integer k, return True if you can deal every number into one of k piles so that all k piles have the same sum, otherwise False. Each number goes into exactly one pile, and a pile can hold any count of numbers.

1 ≤ k ≤ len(nums) ≤ 16 and 1 ≤ nums[i] ≤ 10,000. Some inputs have no answer but a huge number of near misses: those must still finish fast.

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

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

Each pile must reach sum(nums) // k, so first check that the sum divides by k. Then backtrack: place one number at a time into any pile it still fits in, recurse, and undo.

Hint 2

Piles with the same sum are interchangeable: if putting a number on a pile with sum s failed, another pile with sum s fails the same way. Skip it, empty piles included.

Hint 3

Sort the numbers from largest to smallest. Big numbers have the fewest places to go, so a doomed branch runs out of room near the top of the tree instead of deep inside it.

Solution and why it works
pythonO(kⁿ) in the worst case, far less with pruning · O(n + k) recursion depth
def can_deal_evenly(nums: list[int], k: int) -> bool:
    total = sum(nums)
    if total % k:
        return False
    goal = total // k
    nums = sorted(nums, reverse=True)        # big numbers first: dead ends show up early
    if nums[0] > goal:
        return False
    piles = [0] * k

    def place(i: int) -> bool:
        if i == len(nums):
            return True                      # none is over goal and they add up to k·goal
        tried = set()
        for p in range(k):
            if piles[p] in tried or piles[p] + nums[i] > goal:
                continue                     # same sum as a pile already tried: same subtree
            tried.add(piles[p])
            piles[p] += nums[i]
            if place(i + 1):
                return True
            piles[p] -= nums[i]
        return False

    return place(0)

Every pile must reach sum // k and a number only goes on a pile it still fits, so placing them all means every pile hit the goal. Without pruning the search can try up to kⁿ deals, most of them one deal with the piles relabelled. Two cuts fix it: skip a pile whose sum equals one already tried for this number (empty piles too), and place big numbers first, so a hopeless branch fails near the root. The plain search is correct but explodes on near misses.