Filling Bookcase Shelves — LeetCode 1105 Python Solution

MediumArrayDynamic Programming
Problem
#1105
Reading time
2 min

The 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.

Example

Input
books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4
Output
6
Explanation
The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.

Python solution

Python
class Solution:
    def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
        n = len(books)
        f = [0] * (n + 1)
        for i, (w, h) in enumerate(books, 1):
            f[i] = f[i - 1] + h
            for j in range(i - 1, 0, -1):
                w += books[j - 1][0]
                if w > shelfWidth:
                    break
                h = max(h, books[j - 1][1])
                f[i] = min(f[i], f[j - 1] + h)
        return f[n]

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1105. Filling Bookcase Shelves is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1105. Filling Bookcase Shelves?
LeetCode 1105. Filling Bookcase Shelves is rated Medium on LeetCode.
What is the time complexity of LeetCode 1105. Filling Bookcase Shelves?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1105. Filling Bookcase Shelves?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1105. Filling Bookcase Shelves cover?
LeetCode 1105. Filling Bookcase Shelves is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview