698. Partition to K Equal Sum Subsets

Problem

Intuition

Initially this feels like a DP problem seeing we need to explore all the possibilities and somewhere we can optimise the problem. But it is a simple recursion/DFS problems. That is you check all the possibilities to form the subsets. The recursion tree will not end up with any overlapping subproblems.

That is why it is more important to come up with recursive solution for DP problems rather than pre maturely optimising them.

Coming to this problem, we need to do few pre-checks:

  • Check if totalSum can be divided into "k" equal subsets

  • Explore all the possible paths of building subsets

We pick on element and recursively check if there exists other elements that can form the target sum i.e. totalSum/k. If we find a subset we mark the elements we need as visited using a boolean array.

Time Complexity

O(kβˆ—2n)O(k*2^n)

k -> Number of subsets

n -> Total number of elements in the input array

For all the possible subsets we need to pick or not pick the elements. 2^n

Space Complexity

O(N)

For the visited array.

Solution

Last updated