Building Boxes - 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.

There are however some rules to placing the boxes:

  • You can place the boxes anywhere on the floor.
  • If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.

Given an integer n, return the minimum possible number of boxes touching the floor.

Input & Output

Example 1 — Small Pyramid
$ Input: n = 3
Output: 3
💡 Note: With 3 boxes, we need all 3 on the floor since we cannot stack them optimally. Any stacking would require perfect adjacent support which isn't possible with just 3 boxes.
Example 2 — Perfect Pyramid
$ Input: n = 10
Output: 6
💡 Note: We can build a pyramid with base layer of 6 boxes (arranged in triangular pattern 1+2+3), then add 3 boxes on second level (1+2), then 1 box on top. Total: 6+3+1 = 10 boxes.
Example 3 — Single Box
$ Input: n = 1
Output: 1
💡 Note: With only 1 box, it must be placed on the floor. Minimum floor boxes = 1.

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Building Boxes - Optimal Solution INPUT n = 3 3 boxes to place Cubic room: 3x3x3 Unit cube boxes Stack rule: 4 sides must touch wall/box ALGORITHM STEPS 1 Find Triangular Base Build pyramid from corner T(k) = k*(k+1)/2 2 Pyramid Volume Sum of triangles: P(k) = k*(k+1)*(k+2)/6 3 Find Min Height Find k where P(k) >= n k=2: P(2)=4 >= 3 OK 4 Calculate Floor Boxes Full triangle: T(k-1)=1 Extra needed: n-P(k-1) k=2, P(1)=1, P(2)=4 remaining = 3-1 = 2 floor = T(1) + 2 = 1+2 floor = 3 FINAL RESULT 1 2 3 Floor View (Top) Output: 3 OK - Minimum floor boxes = 3 All 3 boxes touch floor Key Insight: Boxes must be stacked in a corner pyramid pattern - each box on top needs 4 sides supported. The optimal structure forms triangular layers: Layer k has T(k) = k*(k+1)/2 boxes. Total pyramid capacity P(k) = k*(k+1)*(k+2)/6. Find minimum k where P(k) >= n, then add extra floor boxes. TutorialsPoint - Building Boxes | Optimal Solution
Asked in
Google 15 Amazon 12
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen