Place books on the least-full allowed shelf
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests segment tree, simulation and arrays.
You have num_shelves shelves, numbered 0 to num_shelves - 1. All shelves start empty.
Books arrive one at a time. Book i comes with a limit limits[i]. It may only go on shelves 0 through limits[i] - 1. Among those shelves, put it on the shelf that currently holds the fewest books. If several shelves tie, choose the one with the smallest index. Then the next book arrives.
Implement:
def organize_books(num_shelves: int, limits: list[int]) -> list[int]:
...
Return a list with the shelf index each book was placed on, in arrival order.
Constraints
1 <= num_shelves <= 10^50 <= len(limits) <= 10^51 <= limits[i] <= num_shelves
A solution that scans the allowed shelves for every book is too slow at these sizes.
Example 1
num_shelves = 3, limits = [3, 3, 3, 3]
output: [0, 1, 2, 0]
Every book may use all three shelves, so they fill round-robin. The fourth book sees counts [1, 1, 1] and takes shelf 0 by the tie-break.
Example 2
num_shelves = 4, limits = [1, 2, 2, 4, 4]
output: [0, 1, 0, 2, 3]
Book 0 must use shelf 0. Book 1 picks shelf 1 (0 books). Book 2 sees counts [1, 1] on shelves 0..1 and takes shelf 0. Books 3 and 4 fill the empty shelves 2 and 3.
Clarifying questions
- Is
limits[i]an exclusive bound, so the allowed shelves are0..limits[i]-1? - Is the tie-break always the smallest index among the allowed shelves?
- Is an empty
limitsanswered with[]? - Do shelves have a maximum capacity, or can they hold any number of books?
What a strong answer covers
- Names the scan per book (
O(n * m)) and why it is too slow. - Uses a segment tree over shelves storing the minimum
(count, index)pair per range; each book is a prefix-minimum query on[0, limits[i] - 1]and a point update,O(log n)each. - Compares pairs so the tie-break by smallest index comes for free.
- Total
O((n + m) log n)time andO(n)space. - Tests the round-robin example, all limits equal to
1, and decreasing limits.
Follow-ups
- Books can also be removed from shelves.
- Each book has a range
[lo, hi]of allowed shelves instead of a prefix. - Shelves have a capacity; a book with no space left gets
-1.
Where it's asked
What it tests
segment tree · simulation · arrays
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
