Place items into the earliest bin that fits
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's technical phone screen, last asked Aug 2025. It tests bin packing, segment tree and greedy.
You have n bins with given capacities and k items arriving in order. Put each item into the leftmost bin whose remaining capacity is at least the item's size, and subtract the size from that bin. An item that fits nowhere stays unplaced. Return how many items are left unplaced, and do better than scanning every bin for every item.
Interface
Unless you agree on a different interface with the interviewer, assume:
count_unplaced(items: list[int], caps: list[int]) -> int
Example
count_unplaced([2, 3, 5], [4, 6, 2]) -> 1 # 2 -> bin 0 (left 2), 3 -> bin 1 (left 3), 5 fits nowhere
count_unplaced([3, 3, 3, 1], [5, 4]) -> 1 # 3 -> bin 0, 3 -> bin 1, 3 fits nowhere, 1 -> bin 0
count_unplaced([5, 5, 5], [4, 4, 4]) -> 3
Constraints
-
1 <= n + k <= 2 * 10^5; sizes and capacities are non-negative integers. - Items are processed strictly in the given order.
- Target O((n + k) log n).
Clarifying questions
- Can an item of size 0 be placed, and in which bin?
- Does an unplaced item stay unplaced, or can it try again after later changes?
- Do you need each item's bin, or only the count?
What a strong answer covers
- Why the naive scan is O(n · k) and too slow at these sizes.
- A max segment tree over remaining capacities: if the root is smaller than the item, it is unplaced; otherwise descend left whenever the left child's maximum is large enough, which finds the leftmost fitting bin in O(log n). Update the leaf and recompute maxima on the way up.
- O(n) build, O(log n) per item, O(n) memory.
- Edge cases: zero-size items, zero-capacity bins, more items than bins, no bins.
- An alternative some candidates try (a union-find that skips full bins) and why it is not enough on its own: a bin can be too small for one item but fit the next.
Follow-ups
- Return the bin index for each item (-1 when unplaced).
- Items can also be removed later, freeing their space.
- Best fit instead of first fit: the bin with the least remaining room that still fits.
Where it's asked
- Amazon · Technical phone screen · Last asked Aug 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
What it tests
bin packing · segment tree · greedy
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
