Partition to K Equal Sum Subsets

Medium · Backtracking · Array · Backtracking · Dynamic Programming · Bit Manipulation · Bitmask

Problem

Given an integer array nums and an integer k, return true if nums can be split into k non-empty groups that all have the same sum, and false otherwise.

Every element must go into exactly one group.

Examples

Input: nums = [2,1,4,5,6], k = 3
Output: true

The groups {6}, {2, 4} and {1, 5} each add up to 6.

Input: nums = [1,2,3,4], k = 3
Output: false

The total, 10, cannot be divided into three equal whole parts.

Constraints

Approaches

Follow-up

What if you had to return the groups, not just whether they exist? Store, for each reachable mask, the value that reached it. Walking back from the full mask lists the values in the order they were placed, and every time the running sum hits a multiple of the target a group ends.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…