Taro Logo

Filling Bookcase Shelves

Medium
Amazon logo
Amazon
1 view
Topics:
Dynamic Programming

You are given an array books where books[i] = [thickness<sub>i</sub>, height<sub>i</sub>] indicates the thickness and height of the i<sup>th</sup> 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 of the bookcase 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.

  • For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.

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

Example: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6

Can you implement a solution for this problem?

Solution


Naive Approach (Brute Force)

The most straightforward approach is to try every possible combination of books on each shelf and find the arrangement that minimizes the total height. This involves recursion, exploring all possible ways to divide the books among shelves.

  1. Base Case: If we have placed all the books, the height is 0.
  2. Recursive Step: For each book, we have two choices: either place it on the current shelf or start a new shelf.
    • If we place it on the current shelf, check if the shelf's width exceeds shelfWidth. If it does, this branch is invalid.
    • If we start a new shelf, the height increases by the height of the tallest book on the current shelf.
  3. Choose the arrangement that yields the minimum total height.

Time Complexity: O(2n), where n is the number of books. This is because, in the worst case, we might explore every possible subset of books for each shelf.

Space Complexity: O(n), due to the depth of the recursion stack.

This approach will likely lead to a "Time Limit Exceeded" error for larger inputs.

Optimal Approach (Dynamic Programming)

We can optimize this using dynamic programming. Let dp[i] be the minimum height to shelve the first i books. We iterate through the books, calculating dp[i] based on the optimal heights of previous subproblems.

  1. Initialization: dp[0] = 0 (no books, no height).
  2. Iteration: For each i from 1 to n, iterate through all possible positions j where we can start a new shelf (from j = 1 to i).
    • Calculate the width and height of the books from i-j+1 to i.
    • If the width is within the shelfWidth, then the total height is dp[i-j] + height of current shelf.
    • Update dp[i] with the minimum height found so far.
def minHeightShelves(books, shelfWidth):
    n = len(books)
    dp = [float('inf')] * (n + 1)
    dp[0] = 0

    for i in range(1, n + 1):
        width = 0
        height = 0
        for j in range(i, 0, -1):
            width += books[j-1][0]
            height = max(height, books[j-1][1])

            if width <= shelfWidth:
                dp[i] = min(dp[i], dp[j-1] + height)
            else:
                break

    return dp[n]

Time Complexity: O(n2), where n is the number of books. This is because we have nested loops: one iterating through the books and another iterating through possible starting points for each shelf.

Space Complexity: O(n), for the dp array.

Edge Cases and Considerations

  • Empty Input: If the input array books is empty, the minimum height is 0.
  • Single Book: If there's only one book, the minimum height is simply the height of that book.
  • All Books Fit on One Shelf: If the total thickness of all books is less than or equal to shelfWidth, the minimum height is the maximum height among all books.
  • Invalid Input: Each thickness must be less than or equal to shelfWidth.

Example Walkthrough

Let's consider books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]] and shelfWidth = 4.

  • dp[0] = 0
  • i = 1: Placing the first book on a shelf, dp[1] = dp[0] + 1 = 1.
  • i = 2: Placing the second book:
    • Separate shelf: dp[2] = min(dp[2], dp[0] + 3) = 3.
    • Same shelf: width = 1+2 = 3 <= 4, height = max(1, 3) = 3, dp[2] = min(dp[2], dp[0] + 3) = 3. dp[1] + 3.
  • i = 3: Placing the third book:
    • Separate shelf: dp[3] = min(dp[3], dp[0] + 3) = 3.
    • Previous 2 on same shelf: width = 2+2= 4, height = max(3,3) = 3. dp[3] = min(dp[3], dp[1] + 3) = 1+3 = 4
    • All 3 on the same shelf: width = 1+2+2 = 5 > 4. Invalid.
  • Continue this process till dp[7]. Finally, dp[7] will be the minimum height (6).