Taro Logo

Number of Great Partitions

#13 Most AskedHard
0 views
Topics:
ArraysDynamic Programming

You are given an array nums consisting of positive integers and an integer k.

Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k.

Return the number of distinct great partitions. Since the answer may be too large, return it modulo 109 + 7.

Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.

Example 1:

Input: nums = [1,2,3,4], k = 4
Output: 6
Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).

Example 2:

Input: nums = [3,3,3], k = 4
Output: 0
Explanation: There are no great partitions for this array.

Example 3:

Input: nums = [6,6], k = 2
Output: 2
Explanation: We can either put nums[0] in the first partition or in the second partition.
The great partitions will be ([6], [6]) and ([6], [6]).

Constraints:

  • 1 <= nums.length, k <= 1000
  • 1 <= nums[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the `nums` array and the value of `k`?
  2. How are the two groups defined? Does every element of `nums` have to be placed into exactly one of the two groups?
  3. Are partitions considered distinct based on the indices of the elements chosen, or strictly by the multiset of values in each group?
  4. If the total sum of all elements in `nums` is less than $2k$, is the correct output always 0?
  5. Can the array contain duplicate values, and how should they be handled when counting distinct partitions?

Brute Force Solution

Approach

Imagine you have a collection of items and you want to separate them into two distinct piles based on a specific numerical rule. The brute force approach works by systematically exploring every conceivable way to distribute the items and checking if each resulting group meets the criteria.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first item and decide whether to place it into the first pile or the second pile.
  2. Move to the next item and make a choice to place it in either pile, repeating this decision for every single item until all items have been sorted.
  3. Once every item is placed into one of the two piles, calculate the total sum of the items in each pile.
  4. Check if both piles meet the required size condition set by the problem rules.
  5. If both piles successfully meet the condition, remember that you found a valid way to split the items.
  6. Repeat this entire process of sorting and checking for every single possible combination of pile assignments.
  7. Count up all the valid ways you discovered and report that final total as your answer.

Code Implementation

def count_great_partitions(number_list, threshold_sum):
    total_combinations = 2 ** len(number_list)
    valid_partition_count = 0
    modulo_value = 10 ** 9 + 7

    # Iterate through all binary representations to simulate every possible distribution of elements into two piles
    for combination_mask in range(total_combinations):
        first_pile_sum = 0
        second_pile_sum = 0

        for element_index in range(len(number_list)):
            if (combination_mask & (1 << element_index)):
                first_pile_sum += number_list[element_index]
            else:
                second_pile_sum += number_list[element_index]

        # Verify if both resulting piles independently satisfy the minimum sum constraint required by the problem
        if first_pile_sum >= threshold_sum and second_pile_sum >= threshold_sum:
            valid_partition_count = (valid_partition_count + 1) % modulo_value

    return valid_partition_count

Big(O) Analysis

Time Complexity
O(2ⁿ) – For each of the n items in the collection, the algorithm makes a binary choice to place it into either the first or the second pile. As this branching decision is repeated independently for every single item, it generates a total of 2ⁿ distinct partition combinations. Since the algorithm explores all these possible subsets to check their sums, the total operations approximate 2ⁿ, which simplifies to the final Big O time complexity of O(2ⁿ).
Space Complexity
O(n * k) – The auxiliary space is driven by the dynamic programming table or memoization structure used to track subset sums up to the target limit k, where n is the number of elements in the array. This two-dimensional structure stores intermediate results for every possible subset sum from zero up to k across all n items. As the input size n and the target sum k grow, the extra memory required scales proportionally to their product. Ultimately, this simplifies to Big O notation of O(n * k).

Optimal Solution

Approach

Instead of checking every possible way to split the numbers into two groups, we calculate the total number of all possible group combinations and subtract the bad combinations where one group falls below a required size limit. This clever shortcut lets us find the answer much faster by focusing only on the combinations we want to avoid.

Here's how the algorithm would work step-by-step:

  1. First, calculate the sum of all the given numbers to understand the total value we are working with.
  2. Check if the sum of all numbers is smaller than twice the required minimum size limit; if it is, no valid partitions are possible because even the total sum cannot satisfy both groups, so the answer is zero.
  3. If the total sum is large enough, determine the total number of all possible group combinations that can be formed using the given numbers.
  4. Count how many combinations result in a group whose sum is strictly less than the required minimum size limit.
  5. Subtract the count of these too-small combinations from the total number of all possible combinations.
  6. Adjust the result to account for the fact that dividing the numbers into two groups creates mirror images for each valid split.
  7. Finally, ensure the result stays within the standard boundaries by applying the required remainder rule to the final number.

Code Implementation

class Solution:
    def countGreatPartitions(self, input_numbers: list[int], minimum_limit: int) -> int:
        modulo_value = 10**9 + 7
        total_sum = sum(input_numbers)

        # If the total sum is less than twice the minimum limit, no valid partitions can exist.
        if total_sum < 2 * minimum_limit:
            return 0

        total_combinations = pow(2, len(input_numbers), modulo_value)
        dynamic_table = [0] * minimum_limit
        dynamic_table[0] = 1

        for current_number in input_numbers:
            for current_sum in range(minimum_limit - 1, current_number - 1, -1):
                dynamic_table[current_sum] = (dynamic_table[current_sum] + dynamic_table[current_sum - current_number]) % modulo_value

        invalid_combinations = (2 * sum(dynamic_table)) % modulo_value

        # Subtracting invalid combinations from total gives valid ones, accounting for symmetry.
        return (total_combinations - invalid_combinations + modulo_value) % modulo_value

Big(O) Analysis

Time Complexity
O(n * k) – The time complexity is driven by calculating the total sum of the array and then running a subset sum dynamic programming algorithm to count the number of combinations that fall below the required minimum size limit k. Here, n is the number of elements in the input array and k is the target sum limit. The dynamic programming table requires iterating n times with each iteration processing up to k possible subset sum values. This nested dependency results in approximately n times k operations, which simplifies to the final Big O notation.
Space Complexity
O(N * K) – The space complexity is driven by the dynamic programming table used to count the combinations whose sums fall below the required limit, where N represents the number of elements and K represents the sum threshold. Specifically, we maintain a one-dimensional or two-dimensional boolean array of size proportional to the target sum limit to track subset sums. As the input size and the required size limit grow, this auxiliary table scales linearly with the product of the array length and the sum limit. No recursion stack is used since the approach is iterative, keeping the extra memory strictly limited to this tabulation structure. Simplifying this relationship yields an overall auxiliary space complexity of O(N * K).

Edge Cases

Total sum of the array elements is strictly less than 2 times k
How to Handle:
Return 0 immediately because it is impossible for both partitions to have a sum of at least k.
Minimum array length where length is 2 and each element is less than k
How to Handle:
The subset sum logic will correctly result in zero valid partitions and return 0.
All elements in the array are individually greater than or equal to k
How to Handle:
Every non-empty subset will have a sum at least k, allowing the total valid partitions to be computed using the power of 2 minus invalid subsets.
Maximum possible array size and maximum element values leading to large sums
How to Handle:
Use a dynamic programming subset sum approach with modulo arithmetic to prevent integer overflow and maintain polynomial time complexity.
Duplicate values present in the input array nums
How to Handle:
Treat elements as distinct by index in the DP state transition rather than distinct by value to properly count unique structural partitions.
An element in nums is much larger than k, exceeding the target threshold instantly
How to Handle:
Cap the dynamic programming knapsack table size at k minus 1 to optimize space and time complexity since sums beyond k behave identically for our condition.
Extremely large total number of partitions requiring modulo 10 to the 9 plus 7
How to Handle:
Apply modulo arithmetic at every addition and subtraction step to prevent arithmetic overflow and correctly output the answer.
No valid great partitions exist even though total sum is at least 2k
How to Handle:
The DP subset sum tabulation will find no valid subset sums strictly less than k, correctly resulting in 0 after subtracting invalid combinations.
0/45 completed