BackmediumGreedyuncategorizedmedium

Minimum Subsets with Bounded Sum Solution

Problem Statement

You are given an array of integers nums and an integer limit. Your task is to partition the array into the minimum number of disjoint subsets such that the sum of elements in each subset does not exceed limit. Every element in nums must be assigned to exactly one subset. Note that the order of elements within a subset does not matter, but the partitioning must cover all elements exactly once.

Return the minimum number of subsets required to satisfy the condition. If it is impossible to partition the array such that every subset's sum is within the limit (e.g., if any single element exceeds limit), return -1.

This problem requires an optimal grouping strategy to minimize the number of groups while respecting the upper bound on the sum of each group.

Example 1
Input
nums = [3, 1, 2, 4], limit = 5
Output
2

Explanation: We can partition the array into two subsets: {3, 2} with sum 5 and {1, 4} with sum 5. Both sums are <= 5. It is not possible to do it in 1 subset because the total sum is 10, which exceeds 5. Thus, the minimum number of subsets is 2.

Example 2
Input
nums = [1, 1, 1, 1, 1], limit = 3
Output
2

Explanation: The total sum is 5. We can form two subsets: {1, 1, 1} with sum 3 and {1, 1} with sum 2. Both are within the limit. We cannot form a single subset because 5 > 3. Hence, the answer is 2.

Example 3
Input
nums = [10, 20, 30], limit = 25
Output
-1

Explanation: The element 30 exceeds the limit of 25. Since no subset can contain 30 without violating the sum constraint, it is impossible to partition the array. Return -1.

Example 4
Input
nums = [2, 2, 2, 2, 2], limit = 4
Output
3

Explanation: Each subset can contain at most two 2s (sum 4). We have five 2s. We can form {2,2}, {2,2}, and {2}. This requires 3 subsets. It is not possible to do it in 2 subsets because 2 subsets can hold at most 4 elements (sum 8), but we have 5 elements (sum 10). Thus, 3 is the minimum.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= limit <= 10^9
  • The sum of all elements in nums may exceed 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimum Subsets with Bounded Sum — Problem Statement & Solution Guide

GreedyMediumMixed
TimeO(n log n)
|
SpaceO(n)

Problem Description

You are given an array of integers nums and an integer limit. Your task is to partition the array into the minimum number of disjoint subsets such that the sum of elements in each subset does not exceed limit. Every element in nums must be assigned to exactly one subset. Note that the order of elements within a subset does not matter, but the partitioning must cover all elements exactly once.

Return the minimum number of subsets required to satisfy the condition. If it is impossible to partition the array such that every subset's sum is within the limit (e.g., if any single element exceeds limit), return -1.

This problem requires an optimal grouping strategy to minimize the number of groups while respecting the upper bound on the sum of each group.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimum Subsets with Bounded Sum"

medium

WHY DOES IT MATTER?

Bin Packing appears in resource allocation, memory management, and load balancing; mastering its greedy patterns equips engineers to design fast, near‑optimal schedulers for real‑world systems.

OPTIMIZATION CHALLENGE

The key insight is that sorting items descending dramatically reduces the search space because large items constrain bin usage early; this enables a linear scan with a first‑fit placement that approximates the optimum without exponential backtracking.

REAL-WORLD CONNECTION

Think of a delivery truck (the bin) that can carry up to a weight limit; the algorithm decides how to load packages (array items) into the fewest trucks, mirroring fleet‑optimization in logistics and cloud‑instance packing.

In an interview, implement FFD with a balanced binary search tree or multiset to locate the first bin with enough remaining capacity in O(log k) time, where k is the current number of bins, keeping the overall complexity O(n log n).

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n)
💾 Space:O(n)

Core Theory — Why This Approach?

The problem is a classic instance of the Bin Packing problem, where each subset corresponds to a bin with capacity limit and each array element is an item of weight equal to its value. The objective is to minimize the number of bins needed to accommodate all items. A naïve exhaustive search would enumerate every possible partition of the set, which grows super‑exponentially (the Bell numbers) and is infeasible even for modest n (e.g., n = 20). Because Bin Packing is NP‑hard, no polynomial‑time algorithm can guarantee optimality for arbitrary inputs unless P = NP. The most widely used practical paradigm is a greedy approximation: sort items in non‑increasing order and place each item into the first bin that can still accommodate it (First‑Fit Decreasing, FFD). FFD runs in O(n log n) time and provably uses at most 11/9·OPT + 1 bins, which is sufficient for most interview settings where an exact solution is not required. When the input size is tiny (n ≤ 20) a DP over subsets or branch‑and‑bound can be employed to obtain the true optimum, but the greedy approach remains the go‑to strategy for medium‑scale data.

Interview Questions on This Problem

Q1Why is the Minimum Subsets with Bounded Sum problem considered NP‑hard, and what does that imply for designing an exact algorithm?

It reduces to the classic Bin Packing problem, which is known to be NP‑hard; therefore any exact algorithm must explore a combinatorial search space that grows exponentially with n, making it impractical for large inputs.

Q2Explain the First‑Fit Decreasing (FFD) heuristic and its worst‑case approximation guarantee for this problem.

FFD sorts items descending, then iteratively places each item into the first existing bin whose remaining capacity is sufficient; if none exists, it opens a new bin. The guarantee is that FFD uses at most 11/9·OPT + 1 bins, where OPT is the optimal number of bins.

Q3How would you modify the greedy solution if the problem statement restricted each subset to contain at most two elements?

When each subset can hold at most two items, the optimal solution is obtained by sorting the array and using a two‑pointer technique: pair the smallest remaining element with the largest that fits together; if they cannot be paired, the largest goes alone. This runs in O(n log n) time and yields the minimum number of subsets.

Examples

Example 1

Input

nums = [3, 1, 2, 4], limit = 5

Output

2

Explanation: We can partition the array into two subsets: {3, 2} with sum 5 and {1, 4} with sum 5. Both sums are <= 5. It is not possible to do it in 1 subset because the total sum is 10, which exceeds 5. Thus, the minimum number of subsets is 2.

Example 2

Input

nums = [1, 1, 1, 1, 1], limit = 3

Output

2

Explanation: The total sum is 5. We can form two subsets: {1, 1, 1} with sum 3 and {1, 1} with sum 2. Both are within the limit. We cannot form a single subset because 5 > 3. Hence, the answer is 2.

Example 3

Input

nums = [10, 20, 30], limit = 25

Output

-1

Explanation: The element 30 exceeds the limit of 25. Since no subset can contain 30 without violating the sum constraint, it is impossible to partition the array. Return -1.

Example 4

Input

nums = [2, 2, 2, 2, 2], limit = 4

Output

3

Explanation: Each subset can contain at most two 2s (sum 4). We have five 2s. We can form {2,2}, {2,2}, and {2}. This requires 3 subsets. It is not possible to do it in 2 subsets because 2 subsets can hold at most 4 elements (sum 8), but we have 5 elements (sum 10). Thus, 3 is the minimum.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= limit <= 10^9
  • The sum of all elements in nums may exceed 10^9

Optimal Approach & Strategy

Sort the array in descending order and apply First‑Fit Decreasing: for each element, insert it into the earliest existing subset with enough remaining capacity, otherwise start a new subset.

Brute Force Approach

Enumerate every possible partition of the array and count the subsets that respect the limit, keeping the minimum count; this requires exponential time and memory.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
function solution(nums, limit) {
   nums.sort((a, b) => b - a);
   let groups = 0;
   let sum = 0;
   for (let i = 0; i < nums.length; i++) {
       if (sum + nums[i] > limit) {
           groups++;
           sum = 0;
       }
       sum += nums[i];
   }
   if (sum > 0) groups++;
   return groups;
}

Asked in Top Tech Interviews

uncategorizedmediumnone

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.