Python 1105.py
class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
@cache
def deeper(pos, width, height): # width and height refer to the current row only
# last row
if pos == len(books):
return height
w, h = books[pos]
# start new row
best = height + deeper(pos + 1, w, h)
# try to add to previous row (if enough space available)
if width + w <= shelfWidth:
best = min(best, deeper(pos + 1, width + w, max(h, height)))
return best
return deeper(0, 0, 0)
Difficulty
and has an acceptance rate of about 69% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of arranging a sequence of books on shelves with a fixed width while minimizing the total height of the resulting bookshelf. The algorithm processes the books in order, deciding for each book whether to start a new shelf or to place it on the current shelf if space permits. The core of the solution is a depth-first search with memoization that explores all feasible placements and returns the minimal height achievable.
Core Recursive Function
The heart of the solution is the nested function deeper. It receives three arguments: the index of the next book to place (pos), the accumulated width of the current shelf (width), and the height of the current shelf (height). The function returns the minimal total height from the current state to the end of the list.
@cache
def deeper(pos, width, height):
# last row
if pos == len(books):
return height
w, h = books[pos]
# start new row
best = height + deeper(pos + 1, w, h)
# try to add to previous row (if enough space available)
if width + w <= shelfWidth:
best = min(best, deeper(pos + 1, width + w, max(h, height)))
return best
Base Case
When pos equals the length of books, the recursion has processed every book. At this point the function returns the height of the last shelf, which is stored in height. This correctly accounts for the final contribution to the total height.
Decision to Start a New Shelf
The line best = height + deeper(pos + 1, w, h) represents the choice of placing the current book on a new shelf. The height of the completed shelf (height) is added to the result of the recursive call that starts a fresh shelf with the current book’s dimensions (w, h). This ensures that the height of each finished shelf is accumulated exactly once.
Decision to Extend the Current Shelf
The conditional block checks whether the current book fits on the existing shelf: if width + w <= shelfWidth. If the condition holds, the algorithm explores the alternative of keeping the current shelf open. The new width becomes width + w, and the new shelf height is the maximum of the existing shelf height and the current book’s height (max(h, height)). The min operation selects the better of the two alternatives.
Edge Cases Handled
The recursion naturally accommodates several edge conditions without additional code.
When the input list of books is empty, the initial call deeper(0, 0, 0) immediately satisfies the base case, returning 0. This correctly indicates that no height is required.
If a single book’s width exceeds shelfWidth, the condition width + w <= shelfWidth will be false for any existing shelf, forcing the algorithm to start a new shelf for that book. The height contributed by that shelf is simply the book’s own height, which matches the expected outcome.
When shelfWidth is zero, the condition for extending a shelf never succeeds, so each book is forced onto its own shelf. The total height becomes the sum of all individual book heights, which is the only feasible arrangement.
Books with varying heights are handled by the max(h, height) expression, ensuring that the shelf height always reflects the tallest book placed on that shelf.
The algorithm respects the original order of the books because it processes them sequentially based on the index pos. No reordering is performed, guaranteeing that the solution adheres to the problem’s ordering constraint.
Performance Optimizations
The most significant optimization is the use of the @cache decorator on the deeper function. This memoization caches the result of each unique combination of (pos, width, height). Since the recursive exploration can revisit the same state many times through different decision paths, caching eliminates redundant calculations and dramatically reduces the number of recursive calls.
By limiting the state to the current position and the dimensions of the active shelf, the algorithm avoids storing the entire arrangement history. This compact representation keeps the cache size manageable while still capturing all information needed to compute the optimal height from any point onward.
The recursion is tail-aware in the sense that each call either adds the height of a completed shelf or updates the current shelf’s dimensions. This design prevents unnecessary copying of large data structures and keeps the overhead per call low.
Overall, the combination of depth-first exploration with memoization yields an efficient solution that scales well with the number of books and the range of possible shelf widths.
ELI5 - Simplified Explanation
Imagine a long row of books that need to be put onto shelves. There is a special tool that helps figure out the best way to stack them so the library stays as short as possible.
The code starts by looking at every book one by one. For each book, there are two choices to make. The first choice is to finish the current shelf and start a brand new one right above it. Because the new shelf starts fresh, the height changes based on that book.
The second choice is to see if the book can fit on the shelf that is already being filled. If there is enough room left on that shelf, the book gets placed next to the others. When a book is added to an existing shelf, the height of that shelf might grow if the new book is taller than the ones already there.
By looking at both choices for every single book, the system keeps track of which plan results in the shortest total stack of shelves. It remembers the calculations it has already done so it does not have to think about the same pile of books twice. This helps find an answer that keeps the shelves from getting too high.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Go | C# | Python | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1124: Longest Well-Performing Interval
- problem 1131: Maximum of Absolute Value Expression
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality