hard +40 pts

Partition to k subsets

Determine if an array of positive integers can be partitioned into k subsets of equal sum.

Write a function `can_partition_k_subsets(nums: list[int], k: int) -> bool` that returns `True` if the list of positive integers `nums` can be partitioned into `k` subsets, each with the same sum. If not possible, return `False`. Each element of `nums` must be used in exactly one subset. The order of elements does not matter. You may assume `k` is a positive integer and `nums` may be empty. If `nums` is empty, the only way to partition it into `k` subsets is if `k == 0`. Since `k` is positive, return `False` for an empty list. Examples: - `nums = [4,3,2,3,5,2,1]`, `k = 4` → returns `True` because the subsets are `[5], [1,4], [2,3], [2,3]`. - `nums = [1,2,3,4]`, `k = 3` → returns `False` because the total sum 10 is not divisible by 3. - `nums = [1,2,3,4]`, `k = 2` → returns `True` because `[1,4]` and `[2,3]` each sum to 5.

Constraints

- `1 <= len(nums) <= 16` (but also handle empty list as specified) - `0 < nums[i] <= 1000` - `1 <= k <= 16` - The total sum of `nums` will fit within an int. - Your solution should be efficient enough for the given constraints (backtracking with pruning is acceptable).

Example

>>> can_partition_k_subsets([4,3,2,3,5,2,1], 4)
True
>>> can_partition_k_subsets([1,2,3,4], 3)
False
>>> can_partition_k_subsets([1,2,3,4], 2)
True
>>> can_partition_k_subsets([], 1)
False
40 points ~35 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First check if the total sum is divisible by k. If not, return False immediately.
Sort the numbers in descending order to reduce branching and speed up backtracking.
Use a list of current subset sums (size k) and recursively assign each number to one of the subsets.
To avoid duplicate states, skip assigning a number to an empty subset if a previous empty subset exists.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.