KatInterview

Partition Items Into Bins With Limited Capacity

Dynamic ProgrammingAuto-graded · 17 test cases
MediumAuto-gradedDynamic Programmingdynamic programmingknapsackmemoization

Last updated

Tests the classic bounded knapsack variant where you must determine the minimum number of identical bins needed so each bin's total weight stays within a capacity, using DP to check feasibility.

Partition Items Into Bins With Limited Capacity

You are managing a warehouse that ships items in identical boxes. Each box can hold a total weight of at most capacity. You are given a list of item weights and must pack all items using as few boxes as possible.

However, there is an additional constraint: each box may hold at most max_per_bin items (by count), regardless of total weight.

Write a function that returns the minimum number of boxes needed to ship all items while satisfying both constraints, or -1 if it is impossible (e.g., a single item exceeds capacity).

Task

Given:

  • weights: a list of positive integers representing item weights
  • capacity: an integer, the maximum total weight per box
  • max_per_bin: an integer, the maximum number of items per box

Return the minimum number of boxes required, or -1 if any item cannot fit in a single box (i.e., its weight exceeds capacity).

Strategy

Use dynamic programming. Define the state as the minimum number of boxes needed to pack exactly a prefix of items given that the last (current) box has already accumulated a certain weight and item count. Sorting items in decreasing order of weight is a useful preprocessing step.

Constraints

  • 1 ≤ len(weights) ≤ 100
  • 1 ≤ weights[i] ≤ 1000
  • 1 ≤ capacity ≤ 10_000
  • 1 ≤ max_per_bin ≤ 50
  • If weights is empty, return 0.
  • If any single item's weight exceeds capacity, return -1.
  • Ties in optimal packing strategies are irrelevant — only the count matters.

Examples

Example 1

Input: min_bins([3, 5, 2, 4, 1], 7, 3)

Output: 3

Example 2

Input: min_bins([10, 10, 10], 10, 1)

Output: 3

Example 3

Input: min_bins([1, 2, 3, 4, 5], 15, 5)

Output: 1

Hints

Hint 1

Sort the items in descending order of weight before running DP — this tends to prune the search space dramatically by failing fast when heavy items cannot share a bin.

Hint 2

Define your DP state as (index_of_next_item_to_pack, current_bin_weight_so_far, items_in_current_bin) → minimum total bins opened so far. Use memoization (functools.lru_cache or a dict).

Hint 3

When you place an item, you can either add it to the current bin (if both weight and count constraints allow) or close the current bin and start a new one. The answer is dp(0, 0, 0) + 1 if you model 'bins opened so far' as closed bins only.