Building Boxes — LeetCode 1739 Python Solution
- Problem
- #1739
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\sqrt{n}), where n is the number of boxes given in the problem |
| Space | O(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.