Filling Bookcase Shelves - Problem

You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.

We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf so that the total height of the bookcase has increased by the maximum height of the books we just put down.

We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.

Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.

Input & Output

Example 1 — Basic Case
$ Input: books = [[1,1],[2,3],[2,1],[1,3]], shelfWidth = 4
Output: 6
💡 Note: Optimal arrangement: Shelf 1: [1,1],[2,3] (width=3, height=3), Shelf 2: [2,1] (width=2, height=1), Shelf 3: [1,3] (width=1, height=3). Total height = 3+1+3 = 6.
Example 2 — All Books on One Shelf
$ Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6
Output: 4
💡 Note: All books fit on one shelf: total width = 1+2+3 = 6 ≤ 6, height = max(3,4,2) = 4.
Example 3 — Each Book Separate
$ Input: books = [[3,5],[3,4],[3,3]], shelfWidth = 3
Output: 12
💡 Note: Each book must be on its own shelf since each has width 3. Total height = 5+4+3 = 12.

Constraints

  • 1 ≤ books.length ≤ 1000
  • 1 ≤ thicknessi ≤ shelfWidth ≤ 1000
  • 1 ≤ heighti ≤ 1000

Visualization

Tap to expand
Filling Bookcase Shelves: Minimize Total HeightInput: books = [[1,1],[2,3],[2,1],[1,3]], shelfWidth = 4[1,1][2,3][2,1][1,3]Optimal Arrangement:Height = 6Shelf 1: height 3, Shelf 2: height 1, Shelf 3: height 3 → Total: 6
Understanding the Visualization
1
Input
Books with [thickness, height] and shelf width limit
2
Process
Find optimal way to group consecutive books on shelves
3
Output
Minimum possible total height of bookcase
Key Takeaway
🎯 Key Insight: Use dynamic programming to try all valid shelf partitions and choose the one with minimum total height
Asked in
Amazon 8 Google 6 Microsoft 4 Facebook 3
95.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen