Problem Breakdown
Inventory Packer
Greedy & Bin Packing
Published ·
easy
Try This Problem Yourself
Practice in the AI-enabled editor with real-time feedback
You're given a list of items, each with a weight and a size. The warehouse hands out bins with two caps, a weight limit and a size limit. Assign every item to a bin such that no bin exceeds either limit. The output is a map from item name to the bin id that holds it. The goal is to minimize the number of bins.
Three items packed into two bins. Bin 0 holds Monitor (8kg, 6size) and Keyboard (2kg, 3size) filling the weight cap, and bin 1 holds Mouse (1kg, 1size) because the weight cap left no room in bin 0
The rules impose a few constraints worth tracing through. Items can't be split across bins, and both caps apply at the same time, so a bin holding the Monitor and Keyboard above is full on weight even though it still has a sliver of size room left for the Mouse. The warehouse hands you one method to list the bins you've already opened in creation order and another method to open a fresh bin that returns its new id.
The problem is a classic bin-packing problem. Finding the absolute minimum number of bins is NP-hard, which means there's no known polynomial algorithm that always produces the optimum. What we can do is pick a fast heuristic, a strategy that usually produces a near-optimal answer even though it gives up the guaranteed optimum, that produces a near-optimal count on the inputs we care about.
Pattern: Greedy & Bin Packing
First-Fit and First-Fit Decreasing are classic greedy bin-packing heuristics. You place each item in the first bin it fits and never look back, trading a perfect answer for one that's fast and close.
Solution 1, First-Fit
The simplest workable heuristic is First-Fit. For each item in the order you receive it, walk the existing bins and put the item in the first one that still has room for it. If nothing fits, open a brand-new bin for the item and move on to the next one.
Complexity
Where it breaks
Solution 2, First-Fit Decreasing
Why descending, not ascending
Complexity
Why this passes
Benchmarks
Takeaways
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium
Reading Progress
On This Page