Building Boxes — LeetCode 1739 Python Solution

HardGreedyMathBinary Search
Problem
#1739
Reading time
3 min

The problem

You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length.

Example

Input
n = 3
Output
3
Explanation
The figure above is for the placement of the three boxes.

Python solution

Python
class Solution:
    def minimumBoxes(self, n: int) -> int:
        s, k = 0, 1
        while s + k * (k + 1) // 2 <= n:
            s += k * (k + 1) // 2
            k += 1
        k -= 1
        ans = k * (k + 1) // 2
        k = 1
        while s < n:
            ans += 1
            s += k
            k += 1
        return ans

Complexity

MeasureComplexity
TimeO(\sqrt{n}), where n is the number of boxes given in the problem
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1739. Building Boxes is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1739. Building Boxes?
LeetCode 1739. Building Boxes is rated Hard on LeetCode.
What is the time complexity of LeetCode 1739. Building Boxes?
The Python solution on this page runs in O(\sqrt{n}), where n is the number of boxes given in the problem.
What is the space complexity of LeetCode 1739. Building Boxes?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1739. Building Boxes cover?
LeetCode 1739. Building Boxes is tagged Greedy, Math and Binary Search 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