Surface Area of 3D Shapes - Problem

You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).

After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.

Return the total surface area of the resulting shapes. Note: The bottom face of each shape counts toward its surface area.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[2]]
Output: 10
💡 Note: Single tower with height 2 has 2×4=8 side faces + 1 top + 1 bottom = 10 total faces
Example 2 — Adjacent Towers
$ Input: grid = [[1,2],[3,4]]
Output: 34
💡 Note: Four towers with glued faces: Tower 1: 6 faces, Tower 2: 10 faces, Tower 3: 14 faces, Tower 4: 22 faces, minus hidden connections = 34
Example 3 — Empty and Full
$ Input: grid = [[1,0],[0,2]]
Output: 16
💡 Note: Two separate towers (1 and 2 height) with no connections: 6 + 10 = 16 faces

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 50
  • 0 ≤ grid[i][j] ≤ 50

Visualization

Tap to expand
Surface Area of 3D Shapes INPUT 1x1 Grid with Tower of 2 Cubes v=2 grid = [[2]] n=1, single tower height=2 Cell (0,0): 2 cubes stacked ALGORITHM STEPS 1 Count Top/Bottom Each tower: 2 faces (if v>0) Top: 1 + Bottom: 1 = 2 2 Count Side Faces 4 sides x height = 4 x 2 = 8 Sides exposed: 8 3 Subtract Overlaps Adjacent towers: min(h1,h2) No neighbors: 0 overlap 4 Sum All Faces Total = top + bottom + sides 2 + 8 - 0 = 10 Formula per cell (i,j): area += 2 + 4*v area -= 2*min(v, neighbor) Calculation for grid[[2]]: 2 (top/bot) + 4*2 (sides) = 10 No adjacent cubes to subtract FINAL RESULT TOP: 1 LEFT 2 RIGHT 2 FRONT: 2 | BACK: 2 | BOTTOM: 1 Exposed Faces: Top: 1 Bottom: 1 Sides: 4 x 2 = 8 Total: 1 + 1 + 8 = 10 Output: 10 [OK] Surface area verified Key Insight: For each tower of height v: add 2 (top+bottom) + 4v (all sides). Then subtract hidden faces between adjacent towers: 2 * min(current_height, neighbor_height) for each of the 4 directions. Time: O(n^2) | Space: O(1) -- Direct counting without building the 3D structure. TutorialsPoint - Surface Area of 3D Shapes | Direct Exposed Face Counting
Asked in
Facebook 35 Amazon 28 Google 22
34.0K Views
Medium Frequency
~15 min Avg. Time
890 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