713151. Carpet into Box

Medium

Carpet into Box

Summary

The Carpet into Box problem involves converting a carpet with dimensions W (width) and H (height) into a box with dimensions B (base area). The goal is to minimize the number of boxes required while ensuring that each box can accommodate a portion of the carpet. This problem requires mathematical and algorithmic thinking, particularly in optimizing the packing process.

Detailed Explanation

To solve this problem, we'll first consider the carpet's dimensions and the available space in the box. Let's assume the carpet is cut into rectangular pieces with a fixed length L (the width of each piece). We want to pack these pieces into boxes to minimize waste. To achieve this, we'll create a binary search tree for the carpet pieces based on their lengths.

Here's a step-by-step breakdown:

  1. Create a Binary Search Tree: Initialize an empty binary search tree (BST). Insert each carpet piece into the BST with its length as the key.
  2. Find the Optimal Box Size: Calculate the optimal box size B that can accommodate at least one carpet piece from the BST. This is achieved by finding the maximum value in the BST's left subtree, which represents the shortest pieces that can be packed into a single box.
  3. Pack Carpet Pieces: Iterate through the BST, and for each piece:
    • If its length is less than or equal to B, pack it into the current box (update the box's dimensions).
    • If its length exceeds B, create a new box with dimensions B and pack this piece into it.
  4. Update Box Count: Increment the total box count each time a new box is created.

To analyze the time complexity, consider that we iterate through the carpet pieces once (step 3), and for each piece, we perform constant-time operations to update the box dimensions or create a new box. This yields an O(n) time complexity, where n is the number of carpet pieces. The space complexity remains O(1) since we only use a constant amount of space to store the binary search tree and box dimensions.

Optimized Solutions

Java

View on GeeksforGeeks
public int minBoxes(int W, int H, int L) {
    int boxes = 0;
    int baseArea = W * H;
    for (int i = L; i <= Math.min(W, H); i++) {
        if ((W / i) * (H / i) >= baseArea) {
            boxes++;
            break;
        }
        boxes += (W / i) * (H / i);
    }
    return boxes;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.